blob: b6f3d8f18c4c52c241d83bfe8eea3be12e303dca [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"
Victor Stinner331a6a52019-05-27 16:39:22 +020043#include "pycore_initconfig.h"
Victor Stinner9fc57a32018-11-07 00:44:03 +010044#include "pycore_fileutils.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +010045#include "pycore_object.h"
Victor Stinner43fc3bb2019-05-02 11:54:20 -040046#include "pycore_pylifecycle.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010047#include "pycore_pystate.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000048#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050049#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070050#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000051
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000052#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000053#include <windows.h>
54#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000055
Victor Stinnerfecc4f22019-03-19 14:20:29 +010056/* Uncomment to display statistics on interned strings at exit when
57 using Valgrind or Insecure++. */
58/* #define INTERNED_STATS 1 */
59
60
Larry Hastings61272b72014-01-07 12:41:53 -080061/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090062class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080063[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090064/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
65
66/*[python input]
67class Py_UCS4_converter(CConverter):
68 type = 'Py_UCS4'
69 converter = 'convert_uc'
70
71 def converter_init(self):
72 if self.default is not unspecified:
73 self.c_default = ascii(self.default)
74 if len(self.c_default) > 4 or self.c_default[0] != "'":
75 self.c_default = hex(ord(self.default))
76
77[python start generated code]*/
78/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080079
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000080/* --- Globals ------------------------------------------------------------
81
Serhiy Storchaka05997252013-01-26 12:14:02 +020082NOTE: In the interpreter's initialization phase, some globals are currently
83 initialized dynamically as needed. In the process Unicode objects may
84 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000085
86*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000087
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000088
89#ifdef __cplusplus
90extern "C" {
91#endif
92
Victor Stinner8faf8212011-12-08 22:14:11 +010093/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
94#define MAX_UNICODE 0x10ffff
95
Victor Stinner910337b2011-10-03 03:20:16 +020096#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020097# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020098#else
99# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
100#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +0200101
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200102#define _PyUnicode_UTF8(op) \
103 (((PyCompactUnicodeObject*)(op))->utf8)
104#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200105 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200106 assert(PyUnicode_IS_READY(op)), \
107 PyUnicode_IS_COMPACT_ASCII(op) ? \
108 ((char*)((PyASCIIObject*)(op) + 1)) : \
109 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200110#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200111 (((PyCompactUnicodeObject*)(op))->utf8_length)
112#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200113 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200114 assert(PyUnicode_IS_READY(op)), \
115 PyUnicode_IS_COMPACT_ASCII(op) ? \
116 ((PyASCIIObject*)(op))->length : \
117 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200118#define _PyUnicode_WSTR(op) \
119 (((PyASCIIObject*)(op))->wstr)
120#define _PyUnicode_WSTR_LENGTH(op) \
121 (((PyCompactUnicodeObject*)(op))->wstr_length)
122#define _PyUnicode_LENGTH(op) \
123 (((PyASCIIObject *)(op))->length)
124#define _PyUnicode_STATE(op) \
125 (((PyASCIIObject *)(op))->state)
126#define _PyUnicode_HASH(op) \
127 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200128#define _PyUnicode_KIND(op) \
129 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200130 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200131#define _PyUnicode_GET_LENGTH(op) \
132 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200133 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200134#define _PyUnicode_DATA_ANY(op) \
135 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200136
Victor Stinner910337b2011-10-03 03:20:16 +0200137#undef PyUnicode_READY
138#define PyUnicode_READY(op) \
139 (assert(_PyUnicode_CHECK(op)), \
140 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200141 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100142 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200143
Victor Stinnerc379ead2011-10-03 12:52:27 +0200144#define _PyUnicode_SHARE_UTF8(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
147 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
148#define _PyUnicode_SHARE_WSTR(op) \
149 (assert(_PyUnicode_CHECK(op)), \
150 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
151
Victor Stinner829c0ad2011-10-03 01:08:02 +0200152/* true if the Unicode object has an allocated UTF-8 memory block
153 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200154#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200155 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200156 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200157 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
158
Victor Stinner03490912011-10-03 23:45:12 +0200159/* true if the Unicode object has an allocated wstr memory block
160 (not shared with other data) */
161#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200162 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200163 (!PyUnicode_IS_READY(op) || \
164 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
165
Victor Stinner910337b2011-10-03 03:20:16 +0200166/* Generic helper macro to convert characters of different types.
167 from_type and to_type have to be valid type names, begin and end
168 are pointers to the source characters which should be of type
169 "from_type *". to is a pointer of type "to_type *" and points to the
170 buffer where the result characters are written to. */
171#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
172 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100173 to_type *_to = (to_type *)(to); \
174 const from_type *_iter = (from_type *)(begin); \
175 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200176 Py_ssize_t n = (_end) - (_iter); \
177 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200178 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200179 while (_iter < (_unrolled_end)) { \
180 _to[0] = (to_type) _iter[0]; \
181 _to[1] = (to_type) _iter[1]; \
182 _to[2] = (to_type) _iter[2]; \
183 _to[3] = (to_type) _iter[3]; \
184 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200185 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200186 while (_iter < (_end)) \
187 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200188 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200189
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200190#ifdef MS_WINDOWS
191 /* On Windows, overallocate by 50% is the best factor */
192# define OVERALLOCATE_FACTOR 2
193#else
194 /* On Linux, overallocate by 25% is the best factor */
195# define OVERALLOCATE_FACTOR 4
196#endif
197
Walter Dörwald16807132007-05-25 13:52:07 +0000198/* This dictionary holds all interned unicode strings. Note that references
199 to strings in this dictionary are *not* counted in the string's ob_refcnt.
200 When the interned string reaches a refcnt of 0 the string deallocation
201 function will delete the reference from this dictionary.
202
203 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000204 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000205*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200206static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000207
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000208/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200209static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200210
Serhiy Storchaka678db842013-01-26 12:16:36 +0200211#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200212 do { \
213 if (unicode_empty != NULL) \
214 Py_INCREF(unicode_empty); \
215 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200216 unicode_empty = PyUnicode_New(0, 0); \
217 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200218 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200219 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
220 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200221 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200222 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000223
Serhiy Storchaka678db842013-01-26 12:16:36 +0200224#define _Py_RETURN_UNICODE_EMPTY() \
225 do { \
226 _Py_INCREF_UNICODE_EMPTY(); \
227 return unicode_empty; \
228 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000229
Victor Stinner59423e32018-11-26 13:40:01 +0100230static inline void
231unicode_fill(enum PyUnicode_Kind kind, void *data, Py_UCS4 value,
232 Py_ssize_t start, Py_ssize_t length)
233{
234 assert(0 <= start);
235 assert(kind != PyUnicode_WCHAR_KIND);
236 switch (kind) {
237 case PyUnicode_1BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100238 assert(value <= 0xff);
Victor Stinner59423e32018-11-26 13:40:01 +0100239 Py_UCS1 ch = (unsigned char)value;
240 Py_UCS1 *to = (Py_UCS1 *)data + start;
241 memset(to, ch, length);
242 break;
243 }
244 case PyUnicode_2BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100245 assert(value <= 0xffff);
Victor Stinner59423e32018-11-26 13:40:01 +0100246 Py_UCS2 ch = (Py_UCS2)value;
247 Py_UCS2 *to = (Py_UCS2 *)data + start;
248 const Py_UCS2 *end = to + length;
249 for (; to < end; ++to) *to = ch;
250 break;
251 }
252 case PyUnicode_4BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100253 assert(value <= MAX_UNICODE);
Victor Stinner59423e32018-11-26 13:40:01 +0100254 Py_UCS4 ch = value;
255 Py_UCS4 * to = (Py_UCS4 *)data + start;
256 const Py_UCS4 *end = to + length;
257 for (; to < end; ++to) *to = ch;
258 break;
259 }
260 default: Py_UNREACHABLE();
261 }
262}
263
264
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200265/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700266static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200267_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
Inada Naoki770847a2019-06-24 12:30:24 +0900268static inline void
269_PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer);
Victor Stinner709d23d2019-05-02 14:56:30 -0400270static PyObject *
271unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
272 const char *errors);
273static PyObject *
274unicode_decode_utf8(const char *s, Py_ssize_t size,
275 _Py_error_handler error_handler, const char *errors,
276 Py_ssize_t *consumed);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200277
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200278/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200279static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200280
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000281/* Single character Unicode strings in the Latin-1 range are being
282 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200283static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000284
Christian Heimes190d79e2008-01-30 11:58:22 +0000285/* Fast detection of the most frequent whitespace characters */
286const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000287 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000288/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000289/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000290/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000291/* case 0x000C: * FORM FEED */
292/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000293 0, 1, 1, 1, 1, 1, 0, 0,
294 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000295/* case 0x001C: * FILE SEPARATOR */
296/* case 0x001D: * GROUP SEPARATOR */
297/* case 0x001E: * RECORD SEPARATOR */
298/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000299 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000300/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 1, 0, 0, 0, 0, 0, 0, 0,
302 0, 0, 0, 0, 0, 0, 0, 0,
303 0, 0, 0, 0, 0, 0, 0, 0,
304 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000305
Benjamin Peterson14339b62009-01-31 16:36:08 +0000306 0, 0, 0, 0, 0, 0, 0, 0,
307 0, 0, 0, 0, 0, 0, 0, 0,
308 0, 0, 0, 0, 0, 0, 0, 0,
309 0, 0, 0, 0, 0, 0, 0, 0,
310 0, 0, 0, 0, 0, 0, 0, 0,
311 0, 0, 0, 0, 0, 0, 0, 0,
312 0, 0, 0, 0, 0, 0, 0, 0,
313 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000314};
315
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200316/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200317static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200318static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100319static int unicode_modifiable(PyObject *unicode);
320
Victor Stinnerfe226c02011-10-03 03:52:20 +0200321
Alexander Belopolsky40018472011-02-26 01:02:56 +0000322static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100323_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200324static PyObject *
325_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
326static PyObject *
327_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
328
329static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000330unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000331 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100332 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000333 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
334
Alexander Belopolsky40018472011-02-26 01:02:56 +0000335static void
336raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300337 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100338 PyObject *unicode,
339 Py_ssize_t startpos, Py_ssize_t endpos,
340 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000341
Christian Heimes190d79e2008-01-30 11:58:22 +0000342/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200343static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000344 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000345/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000346/* 0x000B, * LINE TABULATION */
347/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000348/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000349 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000350 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000351/* 0x001C, * FILE SEPARATOR */
352/* 0x001D, * GROUP SEPARATOR */
353/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000354 0, 0, 0, 0, 1, 1, 1, 0,
355 0, 0, 0, 0, 0, 0, 0, 0,
356 0, 0, 0, 0, 0, 0, 0, 0,
357 0, 0, 0, 0, 0, 0, 0, 0,
358 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000359
Benjamin Peterson14339b62009-01-31 16:36:08 +0000360 0, 0, 0, 0, 0, 0, 0, 0,
361 0, 0, 0, 0, 0, 0, 0, 0,
362 0, 0, 0, 0, 0, 0, 0, 0,
363 0, 0, 0, 0, 0, 0, 0, 0,
364 0, 0, 0, 0, 0, 0, 0, 0,
365 0, 0, 0, 0, 0, 0, 0, 0,
366 0, 0, 0, 0, 0, 0, 0, 0,
367 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000368};
369
INADA Naoki3ae20562017-01-16 20:41:20 +0900370static int convert_uc(PyObject *obj, void *addr);
371
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300372#include "clinic/unicodeobject.c.h"
373
Victor Stinner3d4226a2018-08-29 22:21:32 +0200374_Py_error_handler
375_Py_GetErrorHandler(const char *errors)
Victor Stinner50149202015-09-22 00:26:54 +0200376{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200377 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200378 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200379 }
380 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200381 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200382 }
383 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200384 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200385 }
386 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200387 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200388 }
389 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200390 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200391 }
392 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200393 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200394 }
395 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200396 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200397 }
Victor Stinner50149202015-09-22 00:26:54 +0200398 return _Py_ERROR_OTHER;
399}
400
Victor Stinner709d23d2019-05-02 14:56:30 -0400401
402static _Py_error_handler
403get_error_handler_wide(const wchar_t *errors)
404{
405 if (errors == NULL || wcscmp(errors, L"strict") == 0) {
406 return _Py_ERROR_STRICT;
407 }
408 if (wcscmp(errors, L"surrogateescape") == 0) {
409 return _Py_ERROR_SURROGATEESCAPE;
410 }
411 if (wcscmp(errors, L"replace") == 0) {
412 return _Py_ERROR_REPLACE;
413 }
414 if (wcscmp(errors, L"ignore") == 0) {
415 return _Py_ERROR_IGNORE;
416 }
417 if (wcscmp(errors, L"backslashreplace") == 0) {
418 return _Py_ERROR_BACKSLASHREPLACE;
419 }
420 if (wcscmp(errors, L"surrogatepass") == 0) {
421 return _Py_ERROR_SURROGATEPASS;
422 }
423 if (wcscmp(errors, L"xmlcharrefreplace") == 0) {
424 return _Py_ERROR_XMLCHARREFREPLACE;
425 }
426 return _Py_ERROR_OTHER;
427}
428
429
Victor Stinner22eb6892019-06-26 00:51:05 +0200430static inline int
431unicode_check_encoding_errors(const char *encoding, const char *errors)
432{
433 if (encoding == NULL && errors == NULL) {
434 return 0;
435 }
436
437 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
438#ifndef Py_DEBUG
439 /* In release mode, only check in development mode (-X dev) */
440 if (!interp->config.dev_mode) {
441 return 0;
442 }
443#else
444 /* Always check in debug mode */
445#endif
446
447 /* Avoid calling _PyCodec_Lookup() and PyCodec_LookupError() before the
448 codec registry is ready: before_PyUnicode_InitEncodings() is called. */
449 if (!interp->fs_codec.encoding) {
450 return 0;
451 }
452
453 if (encoding != NULL) {
454 PyObject *handler = _PyCodec_Lookup(encoding);
455 if (handler == NULL) {
456 return -1;
457 }
458 Py_DECREF(handler);
459 }
460
461 if (errors != NULL) {
462 PyObject *handler = PyCodec_LookupError(errors);
463 if (handler == NULL) {
464 return -1;
465 }
466 Py_DECREF(handler);
467 }
468 return 0;
469}
470
471
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300472/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
473 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000474Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000475PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000476{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000477#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000478 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000479#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000480 /* This is actually an illegal character, so it should
481 not be passed to unichr. */
482 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000483#endif
484}
485
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200486int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100487_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200488{
489 PyASCIIObject *ascii;
490 unsigned int kind;
491
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200492 _PyObject_ASSERT(op, PyUnicode_Check(op));
Victor Stinner910337b2011-10-03 03:20:16 +0200493
494 ascii = (PyASCIIObject *)op;
495 kind = ascii->state.kind;
496
Victor Stinnera3b334d2011-10-03 13:53:37 +0200497 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200498 _PyObject_ASSERT(op, kind == PyUnicode_1BYTE_KIND);
499 _PyObject_ASSERT(op, ascii->state.ready == 1);
Victor Stinner910337b2011-10-03 03:20:16 +0200500 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200501 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200502 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200503 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200504
Victor Stinnera41463c2011-10-04 01:05:08 +0200505 if (ascii->state.compact == 1) {
506 data = compact + 1;
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200507 _PyObject_ASSERT(op, kind == PyUnicode_1BYTE_KIND
508 || kind == PyUnicode_2BYTE_KIND
509 || kind == PyUnicode_4BYTE_KIND);
510 _PyObject_ASSERT(op, ascii->state.ascii == 0);
511 _PyObject_ASSERT(op, ascii->state.ready == 1);
512 _PyObject_ASSERT(op, compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100513 }
514 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200515 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
516
517 data = unicode->data.any;
518 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200519 _PyObject_ASSERT(op, ascii->length == 0);
520 _PyObject_ASSERT(op, ascii->hash == -1);
521 _PyObject_ASSERT(op, ascii->state.compact == 0);
522 _PyObject_ASSERT(op, ascii->state.ascii == 0);
523 _PyObject_ASSERT(op, ascii->state.ready == 0);
524 _PyObject_ASSERT(op, ascii->state.interned == SSTATE_NOT_INTERNED);
525 _PyObject_ASSERT(op, ascii->wstr != NULL);
526 _PyObject_ASSERT(op, data == NULL);
527 _PyObject_ASSERT(op, compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200528 }
529 else {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200530 _PyObject_ASSERT(op, kind == PyUnicode_1BYTE_KIND
531 || kind == PyUnicode_2BYTE_KIND
532 || kind == PyUnicode_4BYTE_KIND);
533 _PyObject_ASSERT(op, ascii->state.compact == 0);
534 _PyObject_ASSERT(op, ascii->state.ready == 1);
535 _PyObject_ASSERT(op, data != NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200536 if (ascii->state.ascii) {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200537 _PyObject_ASSERT(op, compact->utf8 == data);
538 _PyObject_ASSERT(op, compact->utf8_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200539 }
540 else
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200541 _PyObject_ASSERT(op, compact->utf8 != data);
Victor Stinnera41463c2011-10-04 01:05:08 +0200542 }
543 }
544 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200545 if (
546#if SIZEOF_WCHAR_T == 2
547 kind == PyUnicode_2BYTE_KIND
548#else
549 kind == PyUnicode_4BYTE_KIND
550#endif
551 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200552 {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200553 _PyObject_ASSERT(op, ascii->wstr == data);
554 _PyObject_ASSERT(op, compact->wstr_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200555 } else
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200556 _PyObject_ASSERT(op, ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200557 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200558
559 if (compact->utf8 == NULL)
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200560 _PyObject_ASSERT(op, compact->utf8_length == 0);
Victor Stinnera41463c2011-10-04 01:05:08 +0200561 if (ascii->wstr == NULL)
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200562 _PyObject_ASSERT(op, compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200563 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200564
565 /* check that the best kind is used: O(n) operation */
566 if (check_content && kind != PyUnicode_WCHAR_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200567 Py_ssize_t i;
568 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200569 void *data;
570 Py_UCS4 ch;
571
572 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200573 for (i=0; i < ascii->length; i++)
574 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200575 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200576 if (ch > maxchar)
577 maxchar = ch;
578 }
579 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100580 if (ascii->state.ascii == 0) {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200581 _PyObject_ASSERT(op, maxchar >= 128);
582 _PyObject_ASSERT(op, maxchar <= 255);
Victor Stinner77faf692011-11-20 18:56:05 +0100583 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200584 else
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200585 _PyObject_ASSERT(op, maxchar < 128);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200586 }
Victor Stinner77faf692011-11-20 18:56:05 +0100587 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200588 _PyObject_ASSERT(op, maxchar >= 0x100);
589 _PyObject_ASSERT(op, maxchar <= 0xFFFF);
Victor Stinner77faf692011-11-20 18:56:05 +0100590 }
591 else {
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200592 _PyObject_ASSERT(op, maxchar >= 0x10000);
593 _PyObject_ASSERT(op, maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100594 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200595 _PyObject_ASSERT(op, PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200596 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400597 return 1;
598}
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200599
Victor Stinner910337b2011-10-03 03:20:16 +0200600
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100601static PyObject*
602unicode_result_wchar(PyObject *unicode)
603{
604#ifndef Py_DEBUG
605 Py_ssize_t len;
606
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100607 len = _PyUnicode_WSTR_LENGTH(unicode);
608 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100609 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200610 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100611 }
612
613 if (len == 1) {
614 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100615 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100616 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
617 Py_DECREF(unicode);
618 return latin1_char;
619 }
620 }
621
622 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200623 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100624 return NULL;
625 }
626#else
Victor Stinneraa771272012-10-04 02:32:58 +0200627 assert(Py_REFCNT(unicode) == 1);
628
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100629 /* don't make the result ready in debug mode to ensure that the caller
630 makes the string ready before using it */
631 assert(_PyUnicode_CheckConsistency(unicode, 1));
632#endif
633 return unicode;
634}
635
636static PyObject*
637unicode_result_ready(PyObject *unicode)
638{
639 Py_ssize_t length;
640
641 length = PyUnicode_GET_LENGTH(unicode);
642 if (length == 0) {
643 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100644 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200645 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100646 }
647 return unicode_empty;
648 }
649
650 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200651 void *data = PyUnicode_DATA(unicode);
652 int kind = PyUnicode_KIND(unicode);
653 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100654 if (ch < 256) {
655 PyObject *latin1_char = unicode_latin1[ch];
656 if (latin1_char != NULL) {
657 if (unicode != latin1_char) {
658 Py_INCREF(latin1_char);
659 Py_DECREF(unicode);
660 }
661 return latin1_char;
662 }
663 else {
664 assert(_PyUnicode_CheckConsistency(unicode, 1));
665 Py_INCREF(unicode);
666 unicode_latin1[ch] = unicode;
667 return unicode;
668 }
669 }
670 }
671
672 assert(_PyUnicode_CheckConsistency(unicode, 1));
673 return unicode;
674}
675
676static PyObject*
677unicode_result(PyObject *unicode)
678{
679 assert(_PyUnicode_CHECK(unicode));
680 if (PyUnicode_IS_READY(unicode))
681 return unicode_result_ready(unicode);
682 else
683 return unicode_result_wchar(unicode);
684}
685
Victor Stinnerc4b49542011-12-11 22:44:26 +0100686static PyObject*
687unicode_result_unchanged(PyObject *unicode)
688{
689 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500690 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100691 return NULL;
692 Py_INCREF(unicode);
693 return unicode;
694 }
695 else
696 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100697 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100698}
699
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200700/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
701 ASCII, Latin1, UTF-8, etc. */
702static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200703backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200704 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
705{
Victor Stinnerad771582015-10-09 12:38:53 +0200706 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200707 Py_UCS4 ch;
708 enum PyUnicode_Kind kind;
709 void *data;
710
711 assert(PyUnicode_IS_READY(unicode));
712 kind = PyUnicode_KIND(unicode);
713 data = PyUnicode_DATA(unicode);
714
715 size = 0;
716 /* determine replacement size */
717 for (i = collstart; i < collend; ++i) {
718 Py_ssize_t incr;
719
720 ch = PyUnicode_READ(kind, data, i);
721 if (ch < 0x100)
722 incr = 2+2;
723 else if (ch < 0x10000)
724 incr = 2+4;
725 else {
726 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200727 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200728 }
729 if (size > PY_SSIZE_T_MAX - incr) {
730 PyErr_SetString(PyExc_OverflowError,
731 "encoded result is too long for a Python string");
732 return NULL;
733 }
734 size += incr;
735 }
736
Victor Stinnerad771582015-10-09 12:38:53 +0200737 str = _PyBytesWriter_Prepare(writer, str, size);
738 if (str == NULL)
739 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200740
741 /* generate replacement */
742 for (i = collstart; i < collend; ++i) {
743 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200744 *str++ = '\\';
745 if (ch >= 0x00010000) {
746 *str++ = 'U';
747 *str++ = Py_hexdigits[(ch>>28)&0xf];
748 *str++ = Py_hexdigits[(ch>>24)&0xf];
749 *str++ = Py_hexdigits[(ch>>20)&0xf];
750 *str++ = Py_hexdigits[(ch>>16)&0xf];
751 *str++ = Py_hexdigits[(ch>>12)&0xf];
752 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200753 }
Victor Stinner797485e2015-10-09 03:17:30 +0200754 else if (ch >= 0x100) {
755 *str++ = 'u';
756 *str++ = Py_hexdigits[(ch>>12)&0xf];
757 *str++ = Py_hexdigits[(ch>>8)&0xf];
758 }
759 else
760 *str++ = 'x';
761 *str++ = Py_hexdigits[(ch>>4)&0xf];
762 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200763 }
764 return str;
765}
766
767/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
768 ASCII, Latin1, UTF-8, etc. */
769static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200770xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200771 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
772{
Victor Stinnerad771582015-10-09 12:38:53 +0200773 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200774 Py_UCS4 ch;
775 enum PyUnicode_Kind kind;
776 void *data;
777
778 assert(PyUnicode_IS_READY(unicode));
779 kind = PyUnicode_KIND(unicode);
780 data = PyUnicode_DATA(unicode);
781
782 size = 0;
783 /* determine replacement size */
784 for (i = collstart; i < collend; ++i) {
785 Py_ssize_t incr;
786
787 ch = PyUnicode_READ(kind, data, i);
788 if (ch < 10)
789 incr = 2+1+1;
790 else if (ch < 100)
791 incr = 2+2+1;
792 else if (ch < 1000)
793 incr = 2+3+1;
794 else if (ch < 10000)
795 incr = 2+4+1;
796 else if (ch < 100000)
797 incr = 2+5+1;
798 else if (ch < 1000000)
799 incr = 2+6+1;
800 else {
801 assert(ch <= MAX_UNICODE);
802 incr = 2+7+1;
803 }
804 if (size > PY_SSIZE_T_MAX - incr) {
805 PyErr_SetString(PyExc_OverflowError,
806 "encoded result is too long for a Python string");
807 return NULL;
808 }
809 size += incr;
810 }
811
Victor Stinnerad771582015-10-09 12:38:53 +0200812 str = _PyBytesWriter_Prepare(writer, str, size);
813 if (str == NULL)
814 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200815
816 /* generate replacement */
817 for (i = collstart; i < collend; ++i) {
818 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
819 }
820 return str;
821}
822
Thomas Wouters477c8d52006-05-27 19:21:47 +0000823/* --- Bloom Filters ----------------------------------------------------- */
824
825/* stuff to implement simple "bloom filters" for Unicode characters.
826 to keep things simple, we use a single bitmask, using the least 5
827 bits from each unicode characters as the bit index. */
828
829/* the linebreak mask is set up by Unicode_Init below */
830
Antoine Pitrouf068f942010-01-13 14:19:12 +0000831#if LONG_BIT >= 128
832#define BLOOM_WIDTH 128
833#elif LONG_BIT >= 64
834#define BLOOM_WIDTH 64
835#elif LONG_BIT >= 32
836#define BLOOM_WIDTH 32
837#else
838#error "LONG_BIT is smaller than 32"
839#endif
840
Thomas Wouters477c8d52006-05-27 19:21:47 +0000841#define BLOOM_MASK unsigned long
842
Serhiy Storchaka05997252013-01-26 12:14:02 +0200843static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000844
Antoine Pitrouf068f942010-01-13 14:19:12 +0000845#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000846
Benjamin Peterson29060642009-01-31 22:14:21 +0000847#define BLOOM_LINEBREAK(ch) \
848 ((ch) < 128U ? ascii_linebreak[(ch)] : \
849 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000850
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700851static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200852make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000853{
Victor Stinnera85af502013-04-09 21:53:54 +0200854#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
855 do { \
856 TYPE *data = (TYPE *)PTR; \
857 TYPE *end = data + LEN; \
858 Py_UCS4 ch; \
859 for (; data != end; data++) { \
860 ch = *data; \
861 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
862 } \
863 break; \
864 } while (0)
865
Thomas Wouters477c8d52006-05-27 19:21:47 +0000866 /* calculate simple bloom-style bitmask for a given unicode string */
867
Antoine Pitrouf068f942010-01-13 14:19:12 +0000868 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000869
870 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200871 switch (kind) {
872 case PyUnicode_1BYTE_KIND:
873 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
874 break;
875 case PyUnicode_2BYTE_KIND:
876 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
877 break;
878 case PyUnicode_4BYTE_KIND:
879 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
880 break;
881 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700882 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200883 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000884 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200885
886#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000887}
888
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300889static int
890ensure_unicode(PyObject *obj)
891{
892 if (!PyUnicode_Check(obj)) {
893 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +0200894 "must be str, not %.100s",
895 Py_TYPE(obj)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300896 return -1;
897 }
898 return PyUnicode_READY(obj);
899}
900
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200901/* Compilation of templated routines */
902
903#include "stringlib/asciilib.h"
904#include "stringlib/fastsearch.h"
905#include "stringlib/partition.h"
906#include "stringlib/split.h"
907#include "stringlib/count.h"
908#include "stringlib/find.h"
909#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200910#include "stringlib/undef.h"
911
912#include "stringlib/ucs1lib.h"
913#include "stringlib/fastsearch.h"
914#include "stringlib/partition.h"
915#include "stringlib/split.h"
916#include "stringlib/count.h"
917#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300918#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200919#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200920#include "stringlib/undef.h"
921
922#include "stringlib/ucs2lib.h"
923#include "stringlib/fastsearch.h"
924#include "stringlib/partition.h"
925#include "stringlib/split.h"
926#include "stringlib/count.h"
927#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300928#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200929#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200930#include "stringlib/undef.h"
931
932#include "stringlib/ucs4lib.h"
933#include "stringlib/fastsearch.h"
934#include "stringlib/partition.h"
935#include "stringlib/split.h"
936#include "stringlib/count.h"
937#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300938#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200939#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200940#include "stringlib/undef.h"
941
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200942#include "stringlib/unicodedefs.h"
943#include "stringlib/fastsearch.h"
944#include "stringlib/count.h"
945#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100946#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200947
Guido van Rossumd57fd912000-03-10 22:53:23 +0000948/* --- Unicode Object ----------------------------------------------------- */
949
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700950static inline Py_ssize_t
951findchar(const void *s, int kind,
952 Py_ssize_t size, Py_UCS4 ch,
953 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200954{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200955 switch (kind) {
956 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200957 if ((Py_UCS1) ch != ch)
958 return -1;
959 if (direction > 0)
960 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
961 else
962 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200963 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200964 if ((Py_UCS2) ch != ch)
965 return -1;
966 if (direction > 0)
967 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
968 else
969 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200970 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200971 if (direction > 0)
972 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
973 else
974 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200975 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700976 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200977 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200978}
979
Victor Stinnerafffce42012-10-03 23:03:17 +0200980#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000981/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200982 earlier.
983
984 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
985 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
986 invalid character in Unicode 6.0. */
987static void
988unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
989{
990 int kind = PyUnicode_KIND(unicode);
991 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
992 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
993 if (length <= old_length)
994 return;
995 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
996}
997#endif
998
Victor Stinnerfe226c02011-10-03 03:52:20 +0200999static PyObject*
1000resize_compact(PyObject *unicode, Py_ssize_t length)
1001{
1002 Py_ssize_t char_size;
1003 Py_ssize_t struct_size;
1004 Py_ssize_t new_size;
1005 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +01001006 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +02001007#ifdef Py_DEBUG
1008 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1009#endif
1010
Victor Stinner79891572012-05-03 13:43:07 +02001011 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001012 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +01001013 assert(PyUnicode_IS_COMPACT(unicode));
1014
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001015 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +01001016 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +02001017 struct_size = sizeof(PyASCIIObject);
1018 else
1019 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +02001020 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001021
Victor Stinnerfe226c02011-10-03 03:52:20 +02001022 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1023 PyErr_NoMemory();
1024 return NULL;
1025 }
1026 new_size = (struct_size + (length + 1) * char_size);
1027
Serhiy Storchaka7aa69082015-12-03 01:02:03 +02001028 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1029 PyObject_DEL(_PyUnicode_UTF8(unicode));
1030 _PyUnicode_UTF8(unicode) = NULL;
1031 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1032 }
Victor Stinner84def372011-12-11 20:04:56 +01001033 _Py_DEC_REFTOTAL;
1034 _Py_ForgetReference(unicode);
1035
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03001036 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +01001037 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001038 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001039 PyErr_NoMemory();
1040 return NULL;
1041 }
Victor Stinner84def372011-12-11 20:04:56 +01001042 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001043 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +01001044
Victor Stinnerfe226c02011-10-03 03:52:20 +02001045 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001046 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001047 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +01001048 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +02001049 _PyUnicode_WSTR_LENGTH(unicode) = length;
1050 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01001051 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
1052 PyObject_DEL(_PyUnicode_WSTR(unicode));
1053 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +01001054 if (!PyUnicode_IS_ASCII(unicode))
1055 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01001056 }
Victor Stinnerafffce42012-10-03 23:03:17 +02001057#ifdef Py_DEBUG
1058 unicode_fill_invalid(unicode, old_length);
1059#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001060 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1061 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +02001062 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001063 return unicode;
1064}
1065
Alexander Belopolsky40018472011-02-26 01:02:56 +00001066static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001067resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001068{
Victor Stinner95663112011-10-04 01:03:50 +02001069 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001070 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001071 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001072 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +00001073
Victor Stinnerfe226c02011-10-03 03:52:20 +02001074 if (PyUnicode_IS_READY(unicode)) {
1075 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001076 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001077 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +02001078#ifdef Py_DEBUG
1079 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1080#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001081
1082 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001083 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +02001084 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
1085 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001086
1087 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1088 PyErr_NoMemory();
1089 return -1;
1090 }
1091 new_size = (length + 1) * char_size;
1092
Victor Stinner7a9105a2011-12-12 00:13:42 +01001093 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1094 {
1095 PyObject_DEL(_PyUnicode_UTF8(unicode));
1096 _PyUnicode_UTF8(unicode) = NULL;
1097 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1098 }
1099
Victor Stinnerfe226c02011-10-03 03:52:20 +02001100 data = (PyObject *)PyObject_REALLOC(data, new_size);
1101 if (data == NULL) {
1102 PyErr_NoMemory();
1103 return -1;
1104 }
1105 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001106 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001107 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001108 _PyUnicode_WSTR_LENGTH(unicode) = length;
1109 }
1110 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001111 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001112 _PyUnicode_UTF8_LENGTH(unicode) = length;
1113 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001114 _PyUnicode_LENGTH(unicode) = length;
1115 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001116#ifdef Py_DEBUG
1117 unicode_fill_invalid(unicode, old_length);
1118#endif
Victor Stinner95663112011-10-04 01:03:50 +02001119 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001120 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001121 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001122 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001123 }
Victor Stinner95663112011-10-04 01:03:50 +02001124 assert(_PyUnicode_WSTR(unicode) != NULL);
1125
1126 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001127 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001128 PyErr_NoMemory();
1129 return -1;
1130 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001131 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001132 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001133 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001134 if (!wstr) {
1135 PyErr_NoMemory();
1136 return -1;
1137 }
1138 _PyUnicode_WSTR(unicode) = wstr;
1139 _PyUnicode_WSTR(unicode)[length] = 0;
1140 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001141 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001142 return 0;
1143}
1144
Victor Stinnerfe226c02011-10-03 03:52:20 +02001145static PyObject*
1146resize_copy(PyObject *unicode, Py_ssize_t length)
1147{
1148 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001149 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001150 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001151
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001152 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001153
1154 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1155 if (copy == NULL)
1156 return NULL;
1157
1158 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001159 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001160 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001161 }
1162 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001163 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001164
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001165 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001166 if (w == NULL)
1167 return NULL;
1168 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1169 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001170 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001171 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001172 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001173 }
1174}
1175
Guido van Rossumd57fd912000-03-10 22:53:23 +00001176/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001177 Ux0000 terminated; some code (e.g. new_identifier)
1178 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001179
1180 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001181 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001182
1183*/
1184
Alexander Belopolsky40018472011-02-26 01:02:56 +00001185static PyUnicodeObject *
1186_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001187{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001188 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001189 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001190
Thomas Wouters477c8d52006-05-27 19:21:47 +00001191 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001192 if (length == 0 && unicode_empty != NULL) {
1193 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001194 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001195 }
1196
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001197 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001198 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001199 return (PyUnicodeObject *)PyErr_NoMemory();
1200 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201 if (length < 0) {
1202 PyErr_SetString(PyExc_SystemError,
1203 "Negative size passed to _PyUnicode_New");
1204 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001205 }
1206
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001207 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1208 if (unicode == NULL)
1209 return NULL;
1210 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001211
1212 _PyUnicode_WSTR_LENGTH(unicode) = length;
1213 _PyUnicode_HASH(unicode) = -1;
1214 _PyUnicode_STATE(unicode).interned = 0;
1215 _PyUnicode_STATE(unicode).kind = 0;
1216 _PyUnicode_STATE(unicode).compact = 0;
1217 _PyUnicode_STATE(unicode).ready = 0;
1218 _PyUnicode_STATE(unicode).ascii = 0;
1219 _PyUnicode_DATA_ANY(unicode) = NULL;
1220 _PyUnicode_LENGTH(unicode) = 0;
1221 _PyUnicode_UTF8(unicode) = NULL;
1222 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1225 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001226 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001227 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001228 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001230
Jeremy Hyltond8082792003-09-16 19:41:39 +00001231 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001232 * the caller fails before initializing str -- unicode_resize()
1233 * reads str[0], and the Keep-Alive optimization can keep memory
1234 * allocated for str alive across a call to unicode_dealloc(unicode).
1235 * We don't want unicode_resize to read uninitialized memory in
1236 * that case.
1237 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001238 _PyUnicode_WSTR(unicode)[0] = 0;
1239 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001240
Victor Stinner7931d9a2011-11-04 00:22:48 +01001241 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001242 return unicode;
1243}
1244
Victor Stinnerf42dc442011-10-02 23:33:16 +02001245static const char*
1246unicode_kind_name(PyObject *unicode)
1247{
Victor Stinner42dfd712011-10-03 14:41:45 +02001248 /* don't check consistency: unicode_kind_name() is called from
1249 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001250 if (!PyUnicode_IS_COMPACT(unicode))
1251 {
1252 if (!PyUnicode_IS_READY(unicode))
1253 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001254 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001255 {
1256 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001257 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001258 return "legacy ascii";
1259 else
1260 return "legacy latin1";
1261 case PyUnicode_2BYTE_KIND:
1262 return "legacy UCS2";
1263 case PyUnicode_4BYTE_KIND:
1264 return "legacy UCS4";
1265 default:
1266 return "<legacy invalid kind>";
1267 }
1268 }
1269 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001270 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001271 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001272 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001273 return "ascii";
1274 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001275 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001276 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001277 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001278 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001279 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001280 default:
1281 return "<invalid compact kind>";
1282 }
1283}
1284
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001285#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001286/* Functions wrapping macros for use in debugger */
Victor Stinnera42de742018-11-22 10:25:22 +01001287char *_PyUnicode_utf8(void *unicode_raw){
1288 PyObject *unicode = _PyObject_CAST(unicode_raw);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001289 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001290}
1291
Victor Stinnera42de742018-11-22 10:25:22 +01001292void *_PyUnicode_compact_data(void *unicode_raw) {
1293 PyObject *unicode = _PyObject_CAST(unicode_raw);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001294 return _PyUnicode_COMPACT_DATA(unicode);
1295}
Victor Stinnera42de742018-11-22 10:25:22 +01001296void *_PyUnicode_data(void *unicode_raw) {
1297 PyObject *unicode = _PyObject_CAST(unicode_raw);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001298 printf("obj %p\n", (void*)unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001299 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1300 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1301 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1302 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1303 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1304 return PyUnicode_DATA(unicode);
1305}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001306
1307void
1308_PyUnicode_Dump(PyObject *op)
1309{
1310 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001311 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1312 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1313 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001314
Victor Stinnera849a4b2011-10-03 12:12:11 +02001315 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001316 {
1317 if (ascii->state.ascii)
1318 data = (ascii + 1);
1319 else
1320 data = (compact + 1);
1321 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001322 else
1323 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001324 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1325 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001326
Victor Stinnera849a4b2011-10-03 12:12:11 +02001327 if (ascii->wstr == data)
1328 printf("shared ");
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001329 printf("wstr=%p", (void *)ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001330
Victor Stinnera3b334d2011-10-03 13:53:37 +02001331 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001332 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001333 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1334 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001335 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001336 (void *)compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001337 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001338 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001339}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001340#endif
1341
1342PyObject *
1343PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1344{
1345 PyObject *obj;
1346 PyCompactUnicodeObject *unicode;
1347 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001348 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001349 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 Py_ssize_t char_size;
1351 Py_ssize_t struct_size;
1352
1353 /* Optimization for empty strings */
1354 if (size == 0 && unicode_empty != NULL) {
1355 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001356 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001357 }
1358
Victor Stinner9e9d6892011-10-04 01:02:02 +02001359 is_ascii = 0;
1360 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001361 struct_size = sizeof(PyCompactUnicodeObject);
1362 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001363 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 char_size = 1;
1365 is_ascii = 1;
1366 struct_size = sizeof(PyASCIIObject);
1367 }
1368 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001369 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001370 char_size = 1;
1371 }
1372 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001373 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001374 char_size = 2;
1375 if (sizeof(wchar_t) == 2)
1376 is_sharing = 1;
1377 }
1378 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001379 if (maxchar > MAX_UNICODE) {
1380 PyErr_SetString(PyExc_SystemError,
1381 "invalid maximum character passed to PyUnicode_New");
1382 return NULL;
1383 }
Victor Stinner8f825062012-04-27 13:55:39 +02001384 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001385 char_size = 4;
1386 if (sizeof(wchar_t) == 4)
1387 is_sharing = 1;
1388 }
1389
1390 /* Ensure we won't overflow the size. */
1391 if (size < 0) {
1392 PyErr_SetString(PyExc_SystemError,
1393 "Negative size passed to PyUnicode_New");
1394 return NULL;
1395 }
1396 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1397 return PyErr_NoMemory();
1398
1399 /* Duplicated allocation code from _PyObject_New() instead of a call to
1400 * PyObject_New() so we are able to allocate space for the object and
1401 * it's data buffer.
1402 */
1403 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1404 if (obj == NULL)
1405 return PyErr_NoMemory();
1406 obj = PyObject_INIT(obj, &PyUnicode_Type);
1407 if (obj == NULL)
1408 return NULL;
1409
1410 unicode = (PyCompactUnicodeObject *)obj;
1411 if (is_ascii)
1412 data = ((PyASCIIObject*)obj) + 1;
1413 else
1414 data = unicode + 1;
1415 _PyUnicode_LENGTH(unicode) = size;
1416 _PyUnicode_HASH(unicode) = -1;
1417 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001418 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001419 _PyUnicode_STATE(unicode).compact = 1;
1420 _PyUnicode_STATE(unicode).ready = 1;
1421 _PyUnicode_STATE(unicode).ascii = is_ascii;
1422 if (is_ascii) {
1423 ((char*)data)[size] = 0;
1424 _PyUnicode_WSTR(unicode) = NULL;
1425 }
Victor Stinner8f825062012-04-27 13:55:39 +02001426 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001427 ((char*)data)[size] = 0;
1428 _PyUnicode_WSTR(unicode) = NULL;
1429 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001430 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001431 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001432 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001433 else {
1434 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001435 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001436 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001437 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001438 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001439 ((Py_UCS4*)data)[size] = 0;
1440 if (is_sharing) {
1441 _PyUnicode_WSTR_LENGTH(unicode) = size;
1442 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1443 }
1444 else {
1445 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1446 _PyUnicode_WSTR(unicode) = NULL;
1447 }
1448 }
Victor Stinner8f825062012-04-27 13:55:39 +02001449#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001450 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001451#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001452 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 return obj;
1454}
1455
1456#if SIZEOF_WCHAR_T == 2
1457/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1458 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001459 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001460
1461 This function assumes that unicode can hold one more code point than wstr
1462 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001463static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001464unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001465 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466{
1467 const wchar_t *iter;
1468 Py_UCS4 *ucs4_out;
1469
Victor Stinner910337b2011-10-03 03:20:16 +02001470 assert(unicode != NULL);
1471 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001472 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1473 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1474
1475 for (iter = begin; iter < end; ) {
1476 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1477 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001478 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1479 && (iter+1) < end
1480 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001481 {
Victor Stinner551ac952011-11-29 22:58:13 +01001482 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001483 iter += 2;
1484 }
1485 else {
1486 *ucs4_out++ = *iter;
1487 iter++;
1488 }
1489 }
1490 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1491 _PyUnicode_GET_LENGTH(unicode)));
1492
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001493}
1494#endif
1495
Victor Stinnercd9950f2011-10-02 00:34:53 +02001496static int
Victor Stinner488fa492011-12-12 00:01:39 +01001497unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001498{
Victor Stinner488fa492011-12-12 00:01:39 +01001499 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001500 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001501 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001502 return -1;
1503 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001504 return 0;
1505}
1506
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001507static int
1508_copy_characters(PyObject *to, Py_ssize_t to_start,
1509 PyObject *from, Py_ssize_t from_start,
1510 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001511{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001512 unsigned int from_kind, to_kind;
1513 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001514
Victor Stinneree4544c2012-05-09 22:24:08 +02001515 assert(0 <= how_many);
1516 assert(0 <= from_start);
1517 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001518 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001519 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001520 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001521
Victor Stinnerd3f08822012-05-29 12:57:52 +02001522 assert(PyUnicode_Check(to));
1523 assert(PyUnicode_IS_READY(to));
1524 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1525
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001526 if (how_many == 0)
1527 return 0;
1528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001529 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001530 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001531 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001532 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001533
Victor Stinnerf1852262012-06-16 16:38:26 +02001534#ifdef Py_DEBUG
1535 if (!check_maxchar
1536 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1537 {
1538 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1539 Py_UCS4 ch;
1540 Py_ssize_t i;
1541 for (i=0; i < how_many; i++) {
1542 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1543 assert(ch <= to_maxchar);
1544 }
1545 }
1546#endif
1547
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001548 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001549 if (check_maxchar
1550 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1551 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001552 /* Writing Latin-1 characters into an ASCII string requires to
1553 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001554 Py_UCS4 max_char;
1555 max_char = ucs1lib_find_max_char(from_data,
1556 (Py_UCS1*)from_data + how_many);
1557 if (max_char >= 128)
1558 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001559 }
Christian Heimesf051e432016-09-13 20:22:02 +02001560 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001561 (char*)from_data + from_kind * from_start,
1562 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001563 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001564 else if (from_kind == PyUnicode_1BYTE_KIND
1565 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001566 {
1567 _PyUnicode_CONVERT_BYTES(
1568 Py_UCS1, Py_UCS2,
1569 PyUnicode_1BYTE_DATA(from) + from_start,
1570 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1571 PyUnicode_2BYTE_DATA(to) + to_start
1572 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001573 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001574 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001575 && to_kind == PyUnicode_4BYTE_KIND)
1576 {
1577 _PyUnicode_CONVERT_BYTES(
1578 Py_UCS1, Py_UCS4,
1579 PyUnicode_1BYTE_DATA(from) + from_start,
1580 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1581 PyUnicode_4BYTE_DATA(to) + to_start
1582 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001583 }
1584 else if (from_kind == PyUnicode_2BYTE_KIND
1585 && to_kind == PyUnicode_4BYTE_KIND)
1586 {
1587 _PyUnicode_CONVERT_BYTES(
1588 Py_UCS2, Py_UCS4,
1589 PyUnicode_2BYTE_DATA(from) + from_start,
1590 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1591 PyUnicode_4BYTE_DATA(to) + to_start
1592 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001593 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001594 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001595 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1596
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001597 if (!check_maxchar) {
1598 if (from_kind == PyUnicode_2BYTE_KIND
1599 && to_kind == PyUnicode_1BYTE_KIND)
1600 {
1601 _PyUnicode_CONVERT_BYTES(
1602 Py_UCS2, Py_UCS1,
1603 PyUnicode_2BYTE_DATA(from) + from_start,
1604 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1605 PyUnicode_1BYTE_DATA(to) + to_start
1606 );
1607 }
1608 else if (from_kind == PyUnicode_4BYTE_KIND
1609 && to_kind == PyUnicode_1BYTE_KIND)
1610 {
1611 _PyUnicode_CONVERT_BYTES(
1612 Py_UCS4, Py_UCS1,
1613 PyUnicode_4BYTE_DATA(from) + from_start,
1614 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1615 PyUnicode_1BYTE_DATA(to) + to_start
1616 );
1617 }
1618 else if (from_kind == PyUnicode_4BYTE_KIND
1619 && to_kind == PyUnicode_2BYTE_KIND)
1620 {
1621 _PyUnicode_CONVERT_BYTES(
1622 Py_UCS4, Py_UCS2,
1623 PyUnicode_4BYTE_DATA(from) + from_start,
1624 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1625 PyUnicode_2BYTE_DATA(to) + to_start
1626 );
1627 }
1628 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001629 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001630 }
1631 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001632 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001633 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001634 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001635 Py_ssize_t i;
1636
Victor Stinnera0702ab2011-09-29 14:14:38 +02001637 for (i=0; i < how_many; i++) {
1638 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001639 if (ch > to_maxchar)
1640 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001641 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1642 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001643 }
1644 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001645 return 0;
1646}
1647
Victor Stinnerd3f08822012-05-29 12:57:52 +02001648void
1649_PyUnicode_FastCopyCharacters(
1650 PyObject *to, Py_ssize_t to_start,
1651 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001652{
1653 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1654}
1655
1656Py_ssize_t
1657PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1658 PyObject *from, Py_ssize_t from_start,
1659 Py_ssize_t how_many)
1660{
1661 int err;
1662
1663 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1664 PyErr_BadInternalCall();
1665 return -1;
1666 }
1667
Benjamin Petersonbac79492012-01-14 13:34:47 -05001668 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001669 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001670 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001671 return -1;
1672
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001673 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001674 PyErr_SetString(PyExc_IndexError, "string index out of range");
1675 return -1;
1676 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001677 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001678 PyErr_SetString(PyExc_IndexError, "string index out of range");
1679 return -1;
1680 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001681 if (how_many < 0) {
1682 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1683 return -1;
1684 }
1685 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001686 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1687 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001688 "Cannot write %zi characters at %zi "
1689 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001690 how_many, to_start, PyUnicode_GET_LENGTH(to));
1691 return -1;
1692 }
1693
1694 if (how_many == 0)
1695 return 0;
1696
Victor Stinner488fa492011-12-12 00:01:39 +01001697 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001698 return -1;
1699
1700 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1701 if (err) {
1702 PyErr_Format(PyExc_SystemError,
1703 "Cannot copy %s characters "
1704 "into a string of %s characters",
1705 unicode_kind_name(from),
1706 unicode_kind_name(to));
1707 return -1;
1708 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001709 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710}
1711
Victor Stinner17222162011-09-28 22:15:37 +02001712/* Find the maximum code point and count the number of surrogate pairs so a
1713 correct string length can be computed before converting a string to UCS4.
1714 This function counts single surrogates as a character and not as a pair.
1715
1716 Return 0 on success, or -1 on error. */
1717static int
1718find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1719 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001720{
1721 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001722 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001723
Victor Stinnerc53be962011-10-02 21:33:54 +02001724 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001725 *num_surrogates = 0;
1726 *maxchar = 0;
1727
1728 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001729#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001730 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1731 && (iter+1) < end
1732 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1733 {
1734 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1735 ++(*num_surrogates);
1736 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001737 }
1738 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001739#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001740 {
1741 ch = *iter;
1742 iter++;
1743 }
1744 if (ch > *maxchar) {
1745 *maxchar = ch;
1746 if (*maxchar > MAX_UNICODE) {
1747 PyErr_Format(PyExc_ValueError,
1748 "character U+%x is not in range [U+0000; U+10ffff]",
1749 ch);
1750 return -1;
1751 }
1752 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001753 }
1754 return 0;
1755}
1756
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001757int
1758_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759{
1760 wchar_t *end;
1761 Py_UCS4 maxchar = 0;
1762 Py_ssize_t num_surrogates;
1763#if SIZEOF_WCHAR_T == 2
1764 Py_ssize_t length_wo_surrogates;
1765#endif
1766
Georg Brandl7597add2011-10-05 16:36:47 +02001767 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001768 strings were created using _PyObject_New() and where no canonical
1769 representation (the str field) has been set yet aka strings
1770 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001771 assert(_PyUnicode_CHECK(unicode));
1772 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001774 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001775 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001776 /* Actually, it should neither be interned nor be anything else: */
1777 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001778
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001779 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001780 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001781 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001782 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783
1784 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001785 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1786 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 PyErr_NoMemory();
1788 return -1;
1789 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001790 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 _PyUnicode_WSTR(unicode), end,
1792 PyUnicode_1BYTE_DATA(unicode));
1793 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1794 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1795 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1796 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001797 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001798 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001799 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 }
1801 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001802 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001803 _PyUnicode_UTF8(unicode) = NULL;
1804 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 }
1806 PyObject_FREE(_PyUnicode_WSTR(unicode));
1807 _PyUnicode_WSTR(unicode) = NULL;
1808 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1809 }
1810 /* In this case we might have to convert down from 4-byte native
1811 wchar_t to 2-byte unicode. */
1812 else if (maxchar < 65536) {
1813 assert(num_surrogates == 0 &&
1814 "FindMaxCharAndNumSurrogatePairs() messed up");
1815
Victor Stinner506f5922011-09-28 22:34:18 +02001816#if SIZEOF_WCHAR_T == 2
1817 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001818 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001819 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1820 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1821 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001822 _PyUnicode_UTF8(unicode) = NULL;
1823 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001824#else
1825 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001826 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001827 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001828 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001829 PyErr_NoMemory();
1830 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001831 }
Victor Stinner506f5922011-09-28 22:34:18 +02001832 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1833 _PyUnicode_WSTR(unicode), end,
1834 PyUnicode_2BYTE_DATA(unicode));
1835 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1836 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1837 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001838 _PyUnicode_UTF8(unicode) = NULL;
1839 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001840 PyObject_FREE(_PyUnicode_WSTR(unicode));
1841 _PyUnicode_WSTR(unicode) = NULL;
1842 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1843#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001844 }
1845 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1846 else {
1847#if SIZEOF_WCHAR_T == 2
1848 /* in case the native representation is 2-bytes, we need to allocate a
1849 new normalized 4-byte version. */
1850 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001851 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1852 PyErr_NoMemory();
1853 return -1;
1854 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001855 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1856 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857 PyErr_NoMemory();
1858 return -1;
1859 }
1860 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1861 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001862 _PyUnicode_UTF8(unicode) = NULL;
1863 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001864 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1865 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001866 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001867 PyObject_FREE(_PyUnicode_WSTR(unicode));
1868 _PyUnicode_WSTR(unicode) = NULL;
1869 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1870#else
1871 assert(num_surrogates == 0);
1872
Victor Stinnerc3c74152011-10-02 20:39:55 +02001873 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001874 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001875 _PyUnicode_UTF8(unicode) = NULL;
1876 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001877 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1878#endif
1879 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1880 }
1881 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001882 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001883 return 0;
1884}
1885
Alexander Belopolsky40018472011-02-26 01:02:56 +00001886static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001887unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001888{
Walter Dörwald16807132007-05-25 13:52:07 +00001889 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001890 case SSTATE_NOT_INTERNED:
1891 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001892
Benjamin Peterson29060642009-01-31 22:14:21 +00001893 case SSTATE_INTERNED_MORTAL:
1894 /* revive dead object temporarily for DelItem */
1895 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001896 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001897 Py_FatalError(
1898 "deletion of interned string failed");
1899 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001900
Benjamin Peterson29060642009-01-31 22:14:21 +00001901 case SSTATE_INTERNED_IMMORTAL:
1902 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001903 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001904
Benjamin Peterson29060642009-01-31 22:14:21 +00001905 default:
1906 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001907 }
1908
Victor Stinner03490912011-10-03 23:45:12 +02001909 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001910 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001911 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001912 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001913 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1914 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001915
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001916 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001917}
1918
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001919#ifdef Py_DEBUG
1920static int
1921unicode_is_singleton(PyObject *unicode)
1922{
1923 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1924 if (unicode == unicode_empty)
1925 return 1;
1926 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1927 {
1928 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1929 if (ch < 256 && unicode_latin1[ch] == unicode)
1930 return 1;
1931 }
1932 return 0;
1933}
1934#endif
1935
Alexander Belopolsky40018472011-02-26 01:02:56 +00001936static int
Victor Stinner488fa492011-12-12 00:01:39 +01001937unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001938{
Victor Stinner488fa492011-12-12 00:01:39 +01001939 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001940 if (Py_REFCNT(unicode) != 1)
1941 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001942 if (_PyUnicode_HASH(unicode) != -1)
1943 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001944 if (PyUnicode_CHECK_INTERNED(unicode))
1945 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001946 if (!PyUnicode_CheckExact(unicode))
1947 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001948#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001949 /* singleton refcount is greater than 1 */
1950 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001951#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001952 return 1;
1953}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001954
Victor Stinnerfe226c02011-10-03 03:52:20 +02001955static int
1956unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1957{
1958 PyObject *unicode;
1959 Py_ssize_t old_length;
1960
1961 assert(p_unicode != NULL);
1962 unicode = *p_unicode;
1963
1964 assert(unicode != NULL);
1965 assert(PyUnicode_Check(unicode));
1966 assert(0 <= length);
1967
Victor Stinner910337b2011-10-03 03:20:16 +02001968 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001969 old_length = PyUnicode_WSTR_LENGTH(unicode);
1970 else
1971 old_length = PyUnicode_GET_LENGTH(unicode);
1972 if (old_length == length)
1973 return 0;
1974
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001975 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001976 _Py_INCREF_UNICODE_EMPTY();
1977 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001978 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001979 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001980 return 0;
1981 }
1982
Victor Stinner488fa492011-12-12 00:01:39 +01001983 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001984 PyObject *copy = resize_copy(unicode, length);
1985 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001986 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001987 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001988 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001989 }
1990
Victor Stinnerfe226c02011-10-03 03:52:20 +02001991 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001992 PyObject *new_unicode = resize_compact(unicode, length);
1993 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001994 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001995 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001996 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001997 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001998 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001999}
2000
Alexander Belopolsky40018472011-02-26 01:02:56 +00002001int
Victor Stinnerfe226c02011-10-03 03:52:20 +02002002PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00002003{
Victor Stinnerfe226c02011-10-03 03:52:20 +02002004 PyObject *unicode;
2005 if (p_unicode == NULL) {
2006 PyErr_BadInternalCall();
2007 return -1;
2008 }
2009 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01002010 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02002011 {
2012 PyErr_BadInternalCall();
2013 return -1;
2014 }
2015 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00002016}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002017
Serhiy Storchakad65c9492015-11-02 14:10:23 +02002018/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01002019
Victor Stinnerb429d3b2012-02-22 21:22:20 +01002020 WARNING: The function doesn't copy the terminating null character and
2021 doesn't check the maximum character (may write a latin1 character in an
2022 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02002023static void
2024unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
2025 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01002026{
2027 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
2028 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02002029 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01002030
2031 switch (kind) {
2032 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01002033 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02002034#ifdef Py_DEBUG
2035 if (PyUnicode_IS_ASCII(unicode)) {
2036 Py_UCS4 maxchar = ucs1lib_find_max_char(
2037 (const Py_UCS1*)str,
2038 (const Py_UCS1*)str + len);
2039 assert(maxchar < 128);
2040 }
2041#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01002042 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02002043 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002044 }
2045 case PyUnicode_2BYTE_KIND: {
2046 Py_UCS2 *start = (Py_UCS2 *)data + index;
2047 Py_UCS2 *ucs2 = start;
2048 assert(index <= PyUnicode_GET_LENGTH(unicode));
2049
Victor Stinner184252a2012-06-16 02:57:41 +02002050 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01002051 *ucs2 = (Py_UCS2)*str;
2052
2053 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02002054 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002055 }
2056 default: {
2057 Py_UCS4 *start = (Py_UCS4 *)data + index;
2058 Py_UCS4 *ucs4 = start;
2059 assert(kind == PyUnicode_4BYTE_KIND);
2060 assert(index <= PyUnicode_GET_LENGTH(unicode));
2061
Victor Stinner184252a2012-06-16 02:57:41 +02002062 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01002063 *ucs4 = (Py_UCS4)*str;
2064
2065 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01002066 }
2067 }
2068}
2069
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002070static PyObject*
2071get_latin1_char(unsigned char ch)
2072{
Victor Stinnera464fc12011-10-02 20:39:30 +02002073 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02002075 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002076 if (!unicode)
2077 return NULL;
2078 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002079 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002080 unicode_latin1[ch] = unicode;
2081 }
2082 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02002083 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002084}
2085
Victor Stinner985a82a2014-01-03 12:53:47 +01002086static PyObject*
2087unicode_char(Py_UCS4 ch)
2088{
2089 PyObject *unicode;
2090
2091 assert(ch <= MAX_UNICODE);
2092
Victor Stinnerf3b46b42014-01-03 13:16:00 +01002093 if (ch < 256)
2094 return get_latin1_char(ch);
2095
Victor Stinner985a82a2014-01-03 12:53:47 +01002096 unicode = PyUnicode_New(1, ch);
2097 if (unicode == NULL)
2098 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002099
2100 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
2101 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01002102 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002103 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01002104 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
2105 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
2106 }
2107 assert(_PyUnicode_CheckConsistency(unicode, 1));
2108 return unicode;
2109}
2110
Alexander Belopolsky40018472011-02-26 01:02:56 +00002111PyObject *
2112PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002113{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002114 if (u == NULL)
2115 return (PyObject*)_PyUnicode_New(size);
2116
2117 if (size < 0) {
2118 PyErr_BadInternalCall();
2119 return NULL;
2120 }
2121
2122 return PyUnicode_FromWideChar(u, size);
2123}
2124
2125PyObject *
2126PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2127{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002128 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002129 Py_UCS4 maxchar = 0;
2130 Py_ssize_t num_surrogates;
2131
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002132 if (u == NULL && size != 0) {
2133 PyErr_BadInternalCall();
2134 return NULL;
2135 }
2136
2137 if (size == -1) {
2138 size = wcslen(u);
2139 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002140
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002141 /* If the Unicode data is known at construction time, we can apply
2142 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002144 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002145 if (size == 0)
2146 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002148 /* Single character Unicode objects in the Latin-1 range are
2149 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002150 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002151 return get_latin1_char((unsigned char)*u);
2152
2153 /* If not empty and not single character, copy the Unicode data
2154 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002155 if (find_maxchar_surrogates(u, u + size,
2156 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002157 return NULL;
2158
Victor Stinner8faf8212011-12-08 22:14:11 +01002159 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002160 if (!unicode)
2161 return NULL;
2162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002163 switch (PyUnicode_KIND(unicode)) {
2164 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002165 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002166 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2167 break;
2168 case PyUnicode_2BYTE_KIND:
2169#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002170 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002171#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002172 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002173 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2174#endif
2175 break;
2176 case PyUnicode_4BYTE_KIND:
2177#if SIZEOF_WCHAR_T == 2
2178 /* This is the only case which has to process surrogates, thus
2179 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002180 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002181#else
2182 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002183 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002184#endif
2185 break;
2186 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002187 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002188 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002189
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002190 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002191}
2192
Alexander Belopolsky40018472011-02-26 01:02:56 +00002193PyObject *
2194PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002195{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002196 if (size < 0) {
2197 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002198 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002199 return NULL;
2200 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002201 if (u != NULL)
2202 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2203 else
2204 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002205}
2206
Alexander Belopolsky40018472011-02-26 01:02:56 +00002207PyObject *
2208PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002209{
2210 size_t size = strlen(u);
2211 if (size > PY_SSIZE_T_MAX) {
2212 PyErr_SetString(PyExc_OverflowError, "input too long");
2213 return NULL;
2214 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002215 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002216}
2217
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002218PyObject *
2219_PyUnicode_FromId(_Py_Identifier *id)
2220{
2221 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002222 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2223 strlen(id->string),
2224 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002225 if (!id->object)
2226 return NULL;
2227 PyUnicode_InternInPlace(&id->object);
2228 assert(!id->next);
2229 id->next = static_strings;
2230 static_strings = id;
2231 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002232 return id->object;
2233}
2234
2235void
2236_PyUnicode_ClearStaticStrings()
2237{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002238 _Py_Identifier *tmp, *s = static_strings;
2239 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002240 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002241 tmp = s->next;
2242 s->next = NULL;
2243 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002244 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002245 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002246}
2247
Benjamin Peterson0df54292012-03-26 14:50:32 -04002248/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002249
Victor Stinnerd3f08822012-05-29 12:57:52 +02002250PyObject*
2251_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002252{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002253 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002254 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002255 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002256#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002257 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002258#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002259 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002260 }
Victor Stinner785938e2011-12-11 20:09:03 +01002261 unicode = PyUnicode_New(size, 127);
2262 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002263 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002264 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2265 assert(_PyUnicode_CheckConsistency(unicode, 1));
2266 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002267}
2268
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002269static Py_UCS4
2270kind_maxchar_limit(unsigned int kind)
2271{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002272 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002273 case PyUnicode_1BYTE_KIND:
2274 return 0x80;
2275 case PyUnicode_2BYTE_KIND:
2276 return 0x100;
2277 case PyUnicode_4BYTE_KIND:
2278 return 0x10000;
2279 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002280 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002281 }
2282}
2283
Victor Stinner702c7342011-10-05 13:50:52 +02002284static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002285_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002287 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002288 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002289
Serhiy Storchaka678db842013-01-26 12:16:36 +02002290 if (size == 0)
2291 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002292 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002293 if (size == 1)
2294 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002295
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002296 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002297 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002298 if (!res)
2299 return NULL;
2300 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002301 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002302 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002303}
2304
Victor Stinnere57b1c02011-09-28 22:20:48 +02002305static PyObject*
2306_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002307{
2308 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002309 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002310
Serhiy Storchaka678db842013-01-26 12:16:36 +02002311 if (size == 0)
2312 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002313 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002314 if (size == 1)
2315 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002316
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002317 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002318 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002319 if (!res)
2320 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002321 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002322 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002323 else {
2324 _PyUnicode_CONVERT_BYTES(
2325 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2326 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002327 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002328 return res;
2329}
2330
Victor Stinnere57b1c02011-09-28 22:20:48 +02002331static PyObject*
2332_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002333{
2334 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002335 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002336
Serhiy Storchaka678db842013-01-26 12:16:36 +02002337 if (size == 0)
2338 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002339 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002340 if (size == 1)
2341 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002342
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002343 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002344 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002345 if (!res)
2346 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002347 if (max_char < 256)
2348 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2349 PyUnicode_1BYTE_DATA(res));
2350 else if (max_char < 0x10000)
2351 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2352 PyUnicode_2BYTE_DATA(res));
2353 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002354 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002355 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002356 return res;
2357}
2358
2359PyObject*
2360PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2361{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002362 if (size < 0) {
2363 PyErr_SetString(PyExc_ValueError, "size must be positive");
2364 return NULL;
2365 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002366 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002367 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002368 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002369 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002370 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002371 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002372 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002373 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002374 PyErr_SetString(PyExc_SystemError, "invalid kind");
2375 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002376 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002377}
2378
Victor Stinnerece58de2012-04-23 23:36:38 +02002379Py_UCS4
2380_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2381{
2382 enum PyUnicode_Kind kind;
2383 void *startptr, *endptr;
2384
2385 assert(PyUnicode_IS_READY(unicode));
2386 assert(0 <= start);
2387 assert(end <= PyUnicode_GET_LENGTH(unicode));
2388 assert(start <= end);
2389
2390 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2391 return PyUnicode_MAX_CHAR_VALUE(unicode);
2392
2393 if (start == end)
2394 return 127;
2395
Victor Stinner94d558b2012-04-27 22:26:58 +02002396 if (PyUnicode_IS_ASCII(unicode))
2397 return 127;
2398
Victor Stinnerece58de2012-04-23 23:36:38 +02002399 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002400 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002401 endptr = (char *)startptr + end * kind;
2402 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002403 switch(kind) {
2404 case PyUnicode_1BYTE_KIND:
2405 return ucs1lib_find_max_char(startptr, endptr);
2406 case PyUnicode_2BYTE_KIND:
2407 return ucs2lib_find_max_char(startptr, endptr);
2408 case PyUnicode_4BYTE_KIND:
2409 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002410 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002411 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002412 }
2413}
2414
Victor Stinner25a4b292011-10-06 12:31:55 +02002415/* Ensure that a string uses the most efficient storage, if it is not the
2416 case: create a new string with of the right kind. Write NULL into *p_unicode
2417 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002418static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002419unicode_adjust_maxchar(PyObject **p_unicode)
2420{
2421 PyObject *unicode, *copy;
2422 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002423 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002424 unsigned int kind;
2425
2426 assert(p_unicode != NULL);
2427 unicode = *p_unicode;
2428 assert(PyUnicode_IS_READY(unicode));
2429 if (PyUnicode_IS_ASCII(unicode))
2430 return;
2431
2432 len = PyUnicode_GET_LENGTH(unicode);
2433 kind = PyUnicode_KIND(unicode);
2434 if (kind == PyUnicode_1BYTE_KIND) {
2435 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002436 max_char = ucs1lib_find_max_char(u, u + len);
2437 if (max_char >= 128)
2438 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002439 }
2440 else if (kind == PyUnicode_2BYTE_KIND) {
2441 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002442 max_char = ucs2lib_find_max_char(u, u + len);
2443 if (max_char >= 256)
2444 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002445 }
2446 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002447 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002448 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002449 max_char = ucs4lib_find_max_char(u, u + len);
2450 if (max_char >= 0x10000)
2451 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002452 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002453 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002454 if (copy != NULL)
2455 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002456 Py_DECREF(unicode);
2457 *p_unicode = copy;
2458}
2459
Victor Stinner034f6cf2011-09-30 02:26:44 +02002460PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002461_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002462{
Victor Stinner87af4f22011-11-21 23:03:47 +01002463 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002464 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002465
Victor Stinner034f6cf2011-09-30 02:26:44 +02002466 if (!PyUnicode_Check(unicode)) {
2467 PyErr_BadInternalCall();
2468 return NULL;
2469 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002470 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002471 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002472
Victor Stinner87af4f22011-11-21 23:03:47 +01002473 length = PyUnicode_GET_LENGTH(unicode);
2474 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002475 if (!copy)
2476 return NULL;
2477 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2478
Christian Heimesf051e432016-09-13 20:22:02 +02002479 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002480 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002481 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002482 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002483}
2484
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002485
Victor Stinnerbc603d12011-10-02 01:00:40 +02002486/* Widen Unicode objects to larger buffers. Don't write terminating null
2487 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002488
2489void*
2490_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2491{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002492 Py_ssize_t len;
2493 void *result;
2494 unsigned int skind;
2495
Benjamin Petersonbac79492012-01-14 13:34:47 -05002496 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002497 return NULL;
2498
2499 len = PyUnicode_GET_LENGTH(s);
2500 skind = PyUnicode_KIND(s);
2501 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002502 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 return NULL;
2504 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002505 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002506 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002507 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002508 if (!result)
2509 return PyErr_NoMemory();
2510 assert(skind == PyUnicode_1BYTE_KIND);
2511 _PyUnicode_CONVERT_BYTES(
2512 Py_UCS1, Py_UCS2,
2513 PyUnicode_1BYTE_DATA(s),
2514 PyUnicode_1BYTE_DATA(s) + len,
2515 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002516 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002517 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002518 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002519 if (!result)
2520 return PyErr_NoMemory();
2521 if (skind == PyUnicode_2BYTE_KIND) {
2522 _PyUnicode_CONVERT_BYTES(
2523 Py_UCS2, Py_UCS4,
2524 PyUnicode_2BYTE_DATA(s),
2525 PyUnicode_2BYTE_DATA(s) + len,
2526 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002527 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002528 else {
2529 assert(skind == PyUnicode_1BYTE_KIND);
2530 _PyUnicode_CONVERT_BYTES(
2531 Py_UCS1, Py_UCS4,
2532 PyUnicode_1BYTE_DATA(s),
2533 PyUnicode_1BYTE_DATA(s) + len,
2534 result);
2535 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002536 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002537 default:
2538 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002539 }
Victor Stinner01698042011-10-04 00:04:26 +02002540 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002541 return NULL;
2542}
2543
2544static Py_UCS4*
2545as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2546 int copy_null)
2547{
2548 int kind;
2549 void *data;
2550 Py_ssize_t len, targetlen;
2551 if (PyUnicode_READY(string) == -1)
2552 return NULL;
2553 kind = PyUnicode_KIND(string);
2554 data = PyUnicode_DATA(string);
2555 len = PyUnicode_GET_LENGTH(string);
2556 targetlen = len;
2557 if (copy_null)
2558 targetlen++;
2559 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002560 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 if (!target) {
2562 PyErr_NoMemory();
2563 return NULL;
2564 }
2565 }
2566 else {
2567 if (targetsize < targetlen) {
2568 PyErr_Format(PyExc_SystemError,
2569 "string is longer than the buffer");
2570 if (copy_null && 0 < targetsize)
2571 target[0] = 0;
2572 return NULL;
2573 }
2574 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002575 if (kind == PyUnicode_1BYTE_KIND) {
2576 Py_UCS1 *start = (Py_UCS1 *) data;
2577 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002579 else if (kind == PyUnicode_2BYTE_KIND) {
2580 Py_UCS2 *start = (Py_UCS2 *) data;
2581 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2582 }
2583 else {
2584 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002585 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 if (copy_null)
2588 target[len] = 0;
2589 return target;
2590}
2591
2592Py_UCS4*
2593PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2594 int copy_null)
2595{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002596 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 PyErr_BadInternalCall();
2598 return NULL;
2599 }
2600 return as_ucs4(string, target, targetsize, copy_null);
2601}
2602
2603Py_UCS4*
2604PyUnicode_AsUCS4Copy(PyObject *string)
2605{
2606 return as_ucs4(string, NULL, 0, 1);
2607}
2608
Victor Stinner15a11362012-10-06 23:48:20 +02002609/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002610 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2611 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2612#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002613
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002614static int
2615unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2616 Py_ssize_t width, Py_ssize_t precision)
2617{
2618 Py_ssize_t length, fill, arglen;
2619 Py_UCS4 maxchar;
2620
2621 if (PyUnicode_READY(str) == -1)
2622 return -1;
2623
2624 length = PyUnicode_GET_LENGTH(str);
2625 if ((precision == -1 || precision >= length)
2626 && width <= length)
2627 return _PyUnicodeWriter_WriteStr(writer, str);
2628
2629 if (precision != -1)
2630 length = Py_MIN(precision, length);
2631
2632 arglen = Py_MAX(length, width);
2633 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2634 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2635 else
2636 maxchar = writer->maxchar;
2637
2638 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2639 return -1;
2640
2641 if (width > length) {
2642 fill = width - length;
2643 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2644 return -1;
2645 writer->pos += fill;
2646 }
2647
2648 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2649 str, 0, length);
2650 writer->pos += length;
2651 return 0;
2652}
2653
2654static int
Victor Stinner998b8062018-09-12 00:23:25 +02002655unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002656 Py_ssize_t width, Py_ssize_t precision)
2657{
2658 /* UTF-8 */
2659 Py_ssize_t length;
2660 PyObject *unicode;
2661 int res;
2662
Serhiy Storchakad586ccb2019-01-12 10:30:35 +02002663 if (precision == -1) {
2664 length = strlen(str);
2665 }
2666 else {
2667 length = 0;
2668 while (length < precision && str[length]) {
2669 length++;
2670 }
2671 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002672 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2673 if (unicode == NULL)
2674 return -1;
2675
2676 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2677 Py_DECREF(unicode);
2678 return res;
2679}
2680
Victor Stinner96865452011-03-01 23:44:09 +00002681static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002682unicode_fromformat_arg(_PyUnicodeWriter *writer,
2683 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002684{
Victor Stinnere215d962012-10-06 23:03:36 +02002685 const char *p;
2686 Py_ssize_t len;
2687 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002688 Py_ssize_t width;
2689 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002690 int longflag;
2691 int longlongflag;
2692 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002693 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002694
2695 p = f;
2696 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002697 zeropad = 0;
2698 if (*f == '0') {
2699 zeropad = 1;
2700 f++;
2701 }
Victor Stinner96865452011-03-01 23:44:09 +00002702
2703 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002704 width = -1;
2705 if (Py_ISDIGIT((unsigned)*f)) {
2706 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002707 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002708 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002709 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002710 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002711 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002712 return NULL;
2713 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002714 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002715 f++;
2716 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002717 }
2718 precision = -1;
2719 if (*f == '.') {
2720 f++;
2721 if (Py_ISDIGIT((unsigned)*f)) {
2722 precision = (*f - '0');
2723 f++;
2724 while (Py_ISDIGIT((unsigned)*f)) {
2725 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2726 PyErr_SetString(PyExc_ValueError,
2727 "precision too big");
2728 return NULL;
2729 }
2730 precision = (precision * 10) + (*f - '0');
2731 f++;
2732 }
2733 }
Victor Stinner96865452011-03-01 23:44:09 +00002734 if (*f == '%') {
2735 /* "%.3%s" => f points to "3" */
2736 f--;
2737 }
2738 }
2739 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002740 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002741 f--;
2742 }
Victor Stinner96865452011-03-01 23:44:09 +00002743
2744 /* Handle %ld, %lu, %lld and %llu. */
2745 longflag = 0;
2746 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002747 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002748 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002749 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002750 longflag = 1;
2751 ++f;
2752 }
Victor Stinner96865452011-03-01 23:44:09 +00002753 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002754 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002755 longlongflag = 1;
2756 f += 2;
2757 }
Victor Stinner96865452011-03-01 23:44:09 +00002758 }
2759 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002760 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002761 size_tflag = 1;
2762 ++f;
2763 }
Victor Stinnere215d962012-10-06 23:03:36 +02002764
2765 if (f[1] == '\0')
2766 writer->overallocate = 0;
2767
2768 switch (*f) {
2769 case 'c':
2770 {
2771 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002772 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002773 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002774 "character argument not in range(0x110000)");
2775 return NULL;
2776 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002777 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002778 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002779 break;
2780 }
2781
2782 case 'i':
2783 case 'd':
2784 case 'u':
2785 case 'x':
2786 {
2787 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002788 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002789 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002790
2791 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002792 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002793 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002794 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002795 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002796 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002797 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002798 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002799 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002800 va_arg(*vargs, size_t));
2801 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002802 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002803 va_arg(*vargs, unsigned int));
2804 }
2805 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002806 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002807 }
2808 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002809 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002810 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002811 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002812 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002813 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002814 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002815 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002816 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002817 va_arg(*vargs, Py_ssize_t));
2818 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002819 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002820 va_arg(*vargs, int));
2821 }
2822 assert(len >= 0);
2823
Victor Stinnere215d962012-10-06 23:03:36 +02002824 if (precision < len)
2825 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002826
2827 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002828 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2829 return NULL;
2830
Victor Stinnere215d962012-10-06 23:03:36 +02002831 if (width > precision) {
2832 Py_UCS4 fillchar;
2833 fill = width - precision;
2834 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002835 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2836 return NULL;
2837 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002838 }
Victor Stinner15a11362012-10-06 23:48:20 +02002839 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002840 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002841 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2842 return NULL;
2843 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002844 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002845
Victor Stinner4a587072013-11-19 12:54:53 +01002846 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2847 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002848 break;
2849 }
2850
2851 case 'p':
2852 {
2853 char number[MAX_LONG_LONG_CHARS];
2854
2855 len = sprintf(number, "%p", va_arg(*vargs, void*));
2856 assert(len >= 0);
2857
2858 /* %p is ill-defined: ensure leading 0x. */
2859 if (number[1] == 'X')
2860 number[1] = 'x';
2861 else if (number[1] != 'x') {
2862 memmove(number + 2, number,
2863 strlen(number) + 1);
2864 number[0] = '0';
2865 number[1] = 'x';
2866 len += 2;
2867 }
2868
Victor Stinner4a587072013-11-19 12:54:53 +01002869 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002870 return NULL;
2871 break;
2872 }
2873
2874 case 's':
2875 {
2876 /* UTF-8 */
2877 const char *s = va_arg(*vargs, const char*);
Victor Stinner998b8062018-09-12 00:23:25 +02002878 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002879 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002880 break;
2881 }
2882
2883 case 'U':
2884 {
2885 PyObject *obj = va_arg(*vargs, PyObject *);
2886 assert(obj && _PyUnicode_CHECK(obj));
2887
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002888 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002889 return NULL;
2890 break;
2891 }
2892
2893 case 'V':
2894 {
2895 PyObject *obj = va_arg(*vargs, PyObject *);
2896 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002897 if (obj) {
2898 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002899 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002900 return NULL;
2901 }
2902 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002903 assert(str != NULL);
Victor Stinner998b8062018-09-12 00:23:25 +02002904 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002905 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002906 }
2907 break;
2908 }
2909
2910 case 'S':
2911 {
2912 PyObject *obj = va_arg(*vargs, PyObject *);
2913 PyObject *str;
2914 assert(obj);
2915 str = PyObject_Str(obj);
2916 if (!str)
2917 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002918 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002919 Py_DECREF(str);
2920 return NULL;
2921 }
2922 Py_DECREF(str);
2923 break;
2924 }
2925
2926 case 'R':
2927 {
2928 PyObject *obj = va_arg(*vargs, PyObject *);
2929 PyObject *repr;
2930 assert(obj);
2931 repr = PyObject_Repr(obj);
2932 if (!repr)
2933 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002934 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002935 Py_DECREF(repr);
2936 return NULL;
2937 }
2938 Py_DECREF(repr);
2939 break;
2940 }
2941
2942 case 'A':
2943 {
2944 PyObject *obj = va_arg(*vargs, PyObject *);
2945 PyObject *ascii;
2946 assert(obj);
2947 ascii = PyObject_ASCII(obj);
2948 if (!ascii)
2949 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002950 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002951 Py_DECREF(ascii);
2952 return NULL;
2953 }
2954 Py_DECREF(ascii);
2955 break;
2956 }
2957
2958 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002959 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002960 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002961 break;
2962
2963 default:
2964 /* if we stumble upon an unknown formatting code, copy the rest
2965 of the format string to the output string. (we cannot just
2966 skip the code, since there's no way to know what's in the
2967 argument list) */
2968 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002969 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002970 return NULL;
2971 f = p+len;
2972 return f;
2973 }
2974
2975 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002976 return f;
2977}
2978
Walter Dörwaldd2034312007-05-18 16:29:38 +00002979PyObject *
2980PyUnicode_FromFormatV(const char *format, va_list vargs)
2981{
Victor Stinnere215d962012-10-06 23:03:36 +02002982 va_list vargs2;
2983 const char *f;
2984 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002985
Victor Stinner8f674cc2013-04-17 23:02:17 +02002986 _PyUnicodeWriter_Init(&writer);
2987 writer.min_length = strlen(format) + 100;
2988 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002989
Benjamin Peterson0c212142016-09-20 20:39:33 -07002990 // Copy varags to be able to pass a reference to a subfunction.
2991 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002992
2993 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002994 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002995 f = unicode_fromformat_arg(&writer, f, &vargs2);
2996 if (f == NULL)
2997 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002998 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002999 else {
Victor Stinnere215d962012-10-06 23:03:36 +02003000 const char *p;
3001 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003002
Victor Stinnere215d962012-10-06 23:03:36 +02003003 p = f;
3004 do
3005 {
3006 if ((unsigned char)*p > 127) {
3007 PyErr_Format(PyExc_ValueError,
3008 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
3009 "string, got a non-ASCII byte: 0x%02x",
3010 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02003011 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02003012 }
3013 p++;
3014 }
3015 while (*p != '\0' && *p != '%');
3016 len = p - f;
3017
3018 if (*p == '\0')
3019 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01003020
3021 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02003022 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02003023
3024 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003025 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003026 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02003027 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02003028 return _PyUnicodeWriter_Finish(&writer);
3029
3030 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02003031 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02003032 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00003033 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003034}
3035
Walter Dörwaldd2034312007-05-18 16:29:38 +00003036PyObject *
3037PyUnicode_FromFormat(const char *format, ...)
3038{
Benjamin Peterson14339b62009-01-31 16:36:08 +00003039 PyObject* ret;
3040 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003041
3042#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00003043 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00003044#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00003045 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00003046#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00003047 ret = PyUnicode_FromFormatV(format, vargs);
3048 va_end(vargs);
3049 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003050}
3051
Serhiy Storchakac46db922018-10-23 22:58:24 +03003052static Py_ssize_t
3053unicode_get_widechar_size(PyObject *unicode)
3054{
3055 Py_ssize_t res;
3056
3057 assert(unicode != NULL);
3058 assert(_PyUnicode_CHECK(unicode));
3059
3060 if (_PyUnicode_WSTR(unicode) != NULL) {
3061 return PyUnicode_WSTR_LENGTH(unicode);
3062 }
3063 assert(PyUnicode_IS_READY(unicode));
3064
3065 res = _PyUnicode_LENGTH(unicode);
3066#if SIZEOF_WCHAR_T == 2
3067 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
3068 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3069 const Py_UCS4 *end = s + res;
3070 for (; s < end; ++s) {
3071 if (*s > 0xFFFF) {
3072 ++res;
3073 }
3074 }
3075 }
3076#endif
3077 return res;
3078}
3079
3080static void
3081unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3082{
3083 const wchar_t *wstr;
3084
3085 assert(unicode != NULL);
3086 assert(_PyUnicode_CHECK(unicode));
3087
3088 wstr = _PyUnicode_WSTR(unicode);
3089 if (wstr != NULL) {
3090 memcpy(w, wstr, size * sizeof(wchar_t));
3091 return;
3092 }
3093 assert(PyUnicode_IS_READY(unicode));
3094
3095 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3096 const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3097 for (; size--; ++s, ++w) {
3098 *w = *s;
3099 }
3100 }
3101 else {
3102#if SIZEOF_WCHAR_T == 4
3103 assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3104 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3105 for (; size--; ++s, ++w) {
3106 *w = *s;
3107 }
3108#else
3109 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
3110 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3111 for (; size--; ++s, ++w) {
3112 Py_UCS4 ch = *s;
3113 if (ch > 0xFFFF) {
3114 assert(ch <= MAX_UNICODE);
3115 /* encode surrogate pair in this case */
3116 *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
3117 if (!size--)
3118 break;
3119 *w = Py_UNICODE_LOW_SURROGATE(ch);
3120 }
3121 else {
3122 *w = ch;
3123 }
3124 }
3125#endif
3126 }
3127}
3128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003129#ifdef HAVE_WCHAR_H
3130
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003131/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00003132
Victor Stinnerd88d9832011-09-06 02:00:05 +02003133 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003134 character) required to convert the unicode object. Ignore size argument.
3135
Victor Stinnerd88d9832011-09-06 02:00:05 +02003136 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003137 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02003138 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003139Py_ssize_t
3140PyUnicode_AsWideChar(PyObject *unicode,
3141 wchar_t *w,
3142 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00003143{
Victor Stinner5593d8a2010-10-02 11:11:27 +00003144 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003145
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003146 if (unicode == NULL) {
3147 PyErr_BadInternalCall();
3148 return -1;
3149 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003150 if (!PyUnicode_Check(unicode)) {
3151 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003152 return -1;
Victor Stinner5593d8a2010-10-02 11:11:27 +00003153 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003154
3155 res = unicode_get_widechar_size(unicode);
3156 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003157 return res + 1;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003158 }
3159
3160 if (size > res) {
3161 size = res + 1;
3162 }
3163 else {
3164 res = size;
3165 }
3166 unicode_copy_as_widechar(unicode, w, size);
3167 return res;
Victor Stinner137c34c2010-09-29 10:25:54 +00003168}
3169
Victor Stinner137c34c2010-09-29 10:25:54 +00003170wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003171PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00003172 Py_ssize_t *size)
3173{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003174 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00003175 Py_ssize_t buflen;
3176
3177 if (unicode == NULL) {
3178 PyErr_BadInternalCall();
3179 return NULL;
3180 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003181 if (!PyUnicode_Check(unicode)) {
3182 PyErr_BadArgument();
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003183 return NULL;
3184 }
3185
Serhiy Storchakac46db922018-10-23 22:58:24 +03003186 buflen = unicode_get_widechar_size(unicode);
3187 buffer = (wchar_t *) PyMem_NEW(wchar_t, (buflen + 1));
Victor Stinner137c34c2010-09-29 10:25:54 +00003188 if (buffer == NULL) {
3189 PyErr_NoMemory();
3190 return NULL;
3191 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003192 unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3193 if (size != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00003194 *size = buflen;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003195 }
3196 else if (wcslen(buffer) != (size_t)buflen) {
3197 PyMem_FREE(buffer);
3198 PyErr_SetString(PyExc_ValueError,
3199 "embedded null character");
3200 return NULL;
3201 }
Victor Stinner137c34c2010-09-29 10:25:54 +00003202 return buffer;
3203}
3204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003205#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003206
Alexander Belopolsky40018472011-02-26 01:02:56 +00003207PyObject *
3208PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003209{
Victor Stinner8faf8212011-12-08 22:14:11 +01003210 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003211 PyErr_SetString(PyExc_ValueError,
3212 "chr() arg not in range(0x110000)");
3213 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003214 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003215
Victor Stinner985a82a2014-01-03 12:53:47 +01003216 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003217}
3218
Alexander Belopolsky40018472011-02-26 01:02:56 +00003219PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003220PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003221{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003222 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003223 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003224 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003225 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003226 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003227 Py_INCREF(obj);
3228 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003229 }
3230 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003231 /* For a Unicode subtype that's not a Unicode object,
3232 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003233 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003234 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003235 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003236 "Can't convert '%.100s' object to str implicitly",
3237 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003238 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003239}
3240
Alexander Belopolsky40018472011-02-26 01:02:56 +00003241PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003242PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003243 const char *encoding,
3244 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003245{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003246 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003247 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003248
Guido van Rossumd57fd912000-03-10 22:53:23 +00003249 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003250 PyErr_BadInternalCall();
3251 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003252 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003253
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003254 /* Decoding bytes objects is the most common case and should be fast */
3255 if (PyBytes_Check(obj)) {
Victor Stinner22eb6892019-06-26 00:51:05 +02003256 if (PyBytes_GET_SIZE(obj) == 0) {
3257 if (unicode_check_encoding_errors(encoding, errors) < 0) {
3258 return NULL;
3259 }
Serhiy Storchaka05997252013-01-26 12:14:02 +02003260 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner22eb6892019-06-26 00:51:05 +02003261 }
3262 return PyUnicode_Decode(
Serhiy Storchaka05997252013-01-26 12:14:02 +02003263 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3264 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003265 }
3266
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003267 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003268 PyErr_SetString(PyExc_TypeError,
3269 "decoding str is not supported");
3270 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003271 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003272
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003273 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3274 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3275 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003276 "decoding to str: need a bytes-like object, %.80s found",
3277 Py_TYPE(obj)->tp_name);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003278 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003279 }
Tim Petersced69f82003-09-16 20:30:58 +00003280
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003281 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003282 PyBuffer_Release(&buffer);
Victor Stinner22eb6892019-06-26 00:51:05 +02003283 if (unicode_check_encoding_errors(encoding, errors) < 0) {
3284 return NULL;
3285 }
Serhiy Storchaka05997252013-01-26 12:14:02 +02003286 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003287 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003288
Serhiy Storchaka05997252013-01-26 12:14:02 +02003289 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003290 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003291 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003292}
3293
Victor Stinnerebe17e02016-10-12 13:57:45 +02003294/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3295 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3296 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003297int
3298_Py_normalize_encoding(const char *encoding,
3299 char *lower,
3300 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003301{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003302 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003303 char *l;
3304 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003305 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003306
Victor Stinner942889a2016-09-05 15:40:10 -07003307 assert(encoding != NULL);
3308
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003309 e = encoding;
3310 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003311 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003312 punct = 0;
3313 while (1) {
3314 char c = *e;
3315 if (c == 0) {
3316 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003317 }
Victor Stinner942889a2016-09-05 15:40:10 -07003318
3319 if (Py_ISALNUM(c) || c == '.') {
3320 if (punct && l != lower) {
3321 if (l == l_end) {
3322 return 0;
3323 }
3324 *l++ = '_';
3325 }
3326 punct = 0;
3327
3328 if (l == l_end) {
3329 return 0;
3330 }
3331 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003332 }
3333 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003334 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003335 }
Victor Stinner942889a2016-09-05 15:40:10 -07003336
3337 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003338 }
3339 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003340 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003341}
3342
Alexander Belopolsky40018472011-02-26 01:02:56 +00003343PyObject *
3344PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003345 Py_ssize_t size,
3346 const char *encoding,
3347 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003348{
3349 PyObject *buffer = NULL, *unicode;
3350 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003351 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3352
Victor Stinner22eb6892019-06-26 00:51:05 +02003353 if (unicode_check_encoding_errors(encoding, errors) < 0) {
3354 return NULL;
3355 }
3356
Victor Stinner942889a2016-09-05 15:40:10 -07003357 if (encoding == NULL) {
3358 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3359 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003360
Fred Drakee4315f52000-05-09 19:53:39 +00003361 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003362 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3363 char *lower = buflower;
3364
3365 /* Fast paths */
3366 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3367 lower += 3;
3368 if (*lower == '_') {
3369 /* Match "utf8" and "utf_8" */
3370 lower++;
3371 }
3372
3373 if (lower[0] == '8' && lower[1] == 0) {
3374 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3375 }
3376 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3377 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3378 }
3379 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3380 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3381 }
3382 }
3383 else {
3384 if (strcmp(lower, "ascii") == 0
3385 || strcmp(lower, "us_ascii") == 0) {
3386 return PyUnicode_DecodeASCII(s, size, errors);
3387 }
Steve Dowercc16be82016-09-08 10:35:16 -07003388 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003389 else if (strcmp(lower, "mbcs") == 0) {
3390 return PyUnicode_DecodeMBCS(s, size, errors);
3391 }
3392 #endif
3393 else if (strcmp(lower, "latin1") == 0
3394 || strcmp(lower, "latin_1") == 0
3395 || strcmp(lower, "iso_8859_1") == 0
3396 || strcmp(lower, "iso8859_1") == 0) {
3397 return PyUnicode_DecodeLatin1(s, size, errors);
3398 }
3399 }
Victor Stinner37296e82010-06-10 13:36:23 +00003400 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003401
3402 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003403 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003404 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003405 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003406 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003407 if (buffer == NULL)
3408 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003409 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003410 if (unicode == NULL)
3411 goto onError;
3412 if (!PyUnicode_Check(unicode)) {
3413 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003414 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003415 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003416 encoding,
3417 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003418 Py_DECREF(unicode);
3419 goto onError;
3420 }
3421 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003422 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003423
Benjamin Peterson29060642009-01-31 22:14:21 +00003424 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003425 Py_XDECREF(buffer);
3426 return NULL;
3427}
3428
Alexander Belopolsky40018472011-02-26 01:02:56 +00003429PyObject *
3430PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003431 const char *encoding,
3432 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003433{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003434 if (!PyUnicode_Check(unicode)) {
3435 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003436 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003437 }
3438
Serhiy Storchaka00939072016-10-27 21:05:49 +03003439 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3440 "PyUnicode_AsDecodedObject() is deprecated; "
3441 "use PyCodec_Decode() to decode from str", 1) < 0)
3442 return NULL;
3443
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003444 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003445 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003446
3447 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003448 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003449}
3450
Alexander Belopolsky40018472011-02-26 01:02:56 +00003451PyObject *
3452PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003453 const char *encoding,
3454 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003455{
3456 PyObject *v;
3457
3458 if (!PyUnicode_Check(unicode)) {
3459 PyErr_BadArgument();
3460 goto onError;
3461 }
3462
Serhiy Storchaka00939072016-10-27 21:05:49 +03003463 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3464 "PyUnicode_AsDecodedUnicode() is deprecated; "
3465 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3466 return NULL;
3467
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003468 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003469 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003470
3471 /* Decode via the codec registry */
3472 v = PyCodec_Decode(unicode, encoding, errors);
3473 if (v == NULL)
3474 goto onError;
3475 if (!PyUnicode_Check(v)) {
3476 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003477 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003478 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003479 encoding,
3480 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003481 Py_DECREF(v);
3482 goto onError;
3483 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003484 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003485
Benjamin Peterson29060642009-01-31 22:14:21 +00003486 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003487 return NULL;
3488}
3489
Alexander Belopolsky40018472011-02-26 01:02:56 +00003490PyObject *
3491PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003492 Py_ssize_t size,
3493 const char *encoding,
3494 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003495{
3496 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003497
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003498 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003499 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003500 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003501 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3502 Py_DECREF(unicode);
3503 return v;
3504}
3505
Alexander Belopolsky40018472011-02-26 01:02:56 +00003506PyObject *
3507PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003508 const char *encoding,
3509 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003510{
3511 PyObject *v;
3512
3513 if (!PyUnicode_Check(unicode)) {
3514 PyErr_BadArgument();
3515 goto onError;
3516 }
3517
Serhiy Storchaka00939072016-10-27 21:05:49 +03003518 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3519 "PyUnicode_AsEncodedObject() is deprecated; "
3520 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3521 "or PyCodec_Encode() for generic encoding", 1) < 0)
3522 return NULL;
3523
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003524 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003525 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003526
3527 /* Encode via the codec registry */
3528 v = PyCodec_Encode(unicode, encoding, errors);
3529 if (v == NULL)
3530 goto onError;
3531 return v;
3532
Benjamin Peterson29060642009-01-31 22:14:21 +00003533 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003534 return NULL;
3535}
3536
Victor Stinner1b579672011-12-17 05:47:23 +01003537
Victor Stinner2cba6b82018-01-10 22:46:15 +01003538static PyObject *
Victor Stinner709d23d2019-05-02 14:56:30 -04003539unicode_encode_locale(PyObject *unicode, _Py_error_handler error_handler,
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003540 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003541{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003542 Py_ssize_t wlen;
3543 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3544 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003545 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003546 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003547
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003548 if ((size_t)wlen != wcslen(wstr)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003549 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003550 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003551 return NULL;
3552 }
3553
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003554 char *str;
3555 size_t error_pos;
3556 const char *reason;
3557 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003558 current_locale, error_handler);
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003559 PyMem_Free(wstr);
3560
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003561 if (res != 0) {
3562 if (res == -2) {
3563 PyObject *exc;
3564 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3565 "locale", unicode,
3566 (Py_ssize_t)error_pos,
3567 (Py_ssize_t)(error_pos+1),
3568 reason);
3569 if (exc != NULL) {
3570 PyCodec_StrictErrors(exc);
3571 Py_DECREF(exc);
3572 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003573 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003574 else if (res == -3) {
3575 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3576 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003577 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003578 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003579 }
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003580 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003581 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003582
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003583 PyObject *bytes = PyBytes_FromString(str);
3584 PyMem_RawFree(str);
3585 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003586}
3587
Victor Stinnerad158722010-10-27 00:25:46 +00003588PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003589PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3590{
Victor Stinner709d23d2019-05-02 14:56:30 -04003591 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3592 return unicode_encode_locale(unicode, error_handler, 1);
Victor Stinner2cba6b82018-01-10 22:46:15 +01003593}
3594
3595PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003596PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003597{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003598 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnere2510952019-05-02 11:28:57 -04003599#ifdef _Py_FORCE_UTF8_FS_ENCODING
Victor Stinner709d23d2019-05-02 14:56:30 -04003600 if (interp->fs_codec.encoding) {
3601 return unicode_encode_utf8(unicode,
3602 interp->fs_codec.error_handler,
3603 interp->fs_codec.errors);
3604 }
3605 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02003606 const wchar_t *filesystem_errors = interp->config.filesystem_errors;
Victor Stinner709d23d2019-05-02 14:56:30 -04003607 _Py_error_handler errors;
Victor Stinner331a6a52019-05-27 16:39:22 +02003608 errors = get_error_handler_wide(filesystem_errors);
Victor Stinner709d23d2019-05-02 14:56:30 -04003609 assert(errors != _Py_ERROR_UNKNOWN);
3610 return unicode_encode_utf8(unicode, errors, NULL);
3611 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003612#else
Victor Stinner793b5312011-04-27 00:24:21 +02003613 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3614 cannot use it to encode and decode filenames before it is loaded. Load
3615 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003616 implementation of the locale codec until the codec registry is
Victor Stinner22eb6892019-06-26 00:51:05 +02003617 initialized and the Python codec is loaded.
3618 See _PyUnicode_InitEncodings(). */
Victor Stinner709d23d2019-05-02 14:56:30 -04003619 if (interp->fs_codec.encoding) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003620 return PyUnicode_AsEncodedString(unicode,
Victor Stinner709d23d2019-05-02 14:56:30 -04003621 interp->fs_codec.encoding,
3622 interp->fs_codec.errors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003623 }
3624 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02003625 const wchar_t *filesystem_errors = interp->config.filesystem_errors;
Victor Stinner709d23d2019-05-02 14:56:30 -04003626 _Py_error_handler errors;
Victor Stinner331a6a52019-05-27 16:39:22 +02003627 errors = get_error_handler_wide(filesystem_errors);
Victor Stinner709d23d2019-05-02 14:56:30 -04003628 assert(errors != _Py_ERROR_UNKNOWN);
3629 return unicode_encode_locale(unicode, errors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003630 }
Victor Stinnerad158722010-10-27 00:25:46 +00003631#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003632}
3633
Alexander Belopolsky40018472011-02-26 01:02:56 +00003634PyObject *
3635PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003636 const char *encoding,
3637 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003638{
3639 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003640 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003641
Guido van Rossumd57fd912000-03-10 22:53:23 +00003642 if (!PyUnicode_Check(unicode)) {
3643 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003644 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003645 }
Fred Drakee4315f52000-05-09 19:53:39 +00003646
Victor Stinner22eb6892019-06-26 00:51:05 +02003647 if (unicode_check_encoding_errors(encoding, errors) < 0) {
3648 return NULL;
3649 }
3650
Victor Stinner942889a2016-09-05 15:40:10 -07003651 if (encoding == NULL) {
3652 return _PyUnicode_AsUTF8String(unicode, errors);
3653 }
3654
Fred Drakee4315f52000-05-09 19:53:39 +00003655 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003656 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3657 char *lower = buflower;
3658
3659 /* Fast paths */
3660 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3661 lower += 3;
3662 if (*lower == '_') {
3663 /* Match "utf8" and "utf_8" */
3664 lower++;
3665 }
3666
3667 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003668 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003669 }
3670 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3671 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3672 }
3673 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3674 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3675 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003676 }
Victor Stinner942889a2016-09-05 15:40:10 -07003677 else {
3678 if (strcmp(lower, "ascii") == 0
3679 || strcmp(lower, "us_ascii") == 0) {
3680 return _PyUnicode_AsASCIIString(unicode, errors);
3681 }
Steve Dowercc16be82016-09-08 10:35:16 -07003682#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003683 else if (strcmp(lower, "mbcs") == 0) {
3684 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3685 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003686#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003687 else if (strcmp(lower, "latin1") == 0 ||
3688 strcmp(lower, "latin_1") == 0 ||
3689 strcmp(lower, "iso_8859_1") == 0 ||
3690 strcmp(lower, "iso8859_1") == 0) {
3691 return _PyUnicode_AsLatin1String(unicode, errors);
3692 }
3693 }
Victor Stinner37296e82010-06-10 13:36:23 +00003694 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003695
3696 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003697 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003698 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003699 return NULL;
3700
3701 /* The normal path */
3702 if (PyBytes_Check(v))
3703 return v;
3704
3705 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003706 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003707 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003708 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003709
3710 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003711 "encoder %s returned bytearray instead of bytes; "
3712 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003713 encoding);
3714 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003715 Py_DECREF(v);
3716 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003717 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003718
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003719 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3720 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003721 Py_DECREF(v);
3722 return b;
3723 }
3724
3725 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003726 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003727 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003728 encoding,
3729 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003730 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003731 return NULL;
3732}
3733
Alexander Belopolsky40018472011-02-26 01:02:56 +00003734PyObject *
3735PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003736 const char *encoding,
3737 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003738{
3739 PyObject *v;
3740
3741 if (!PyUnicode_Check(unicode)) {
3742 PyErr_BadArgument();
3743 goto onError;
3744 }
3745
Serhiy Storchaka00939072016-10-27 21:05:49 +03003746 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3747 "PyUnicode_AsEncodedUnicode() is deprecated; "
3748 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3749 return NULL;
3750
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003751 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003752 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003753
3754 /* Encode via the codec registry */
3755 v = PyCodec_Encode(unicode, encoding, errors);
3756 if (v == NULL)
3757 goto onError;
3758 if (!PyUnicode_Check(v)) {
3759 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003760 "'%.400s' encoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003761 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003762 encoding,
3763 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003764 Py_DECREF(v);
3765 goto onError;
3766 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003767 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003768
Benjamin Peterson29060642009-01-31 22:14:21 +00003769 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003770 return NULL;
3771}
3772
Victor Stinner2cba6b82018-01-10 22:46:15 +01003773static PyObject*
Victor Stinner709d23d2019-05-02 14:56:30 -04003774unicode_decode_locale(const char *str, Py_ssize_t len,
3775 _Py_error_handler errors, int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003776{
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003777 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3778 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003779 return NULL;
3780 }
3781
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003782 wchar_t *wstr;
3783 size_t wlen;
3784 const char *reason;
3785 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
Victor Stinner709d23d2019-05-02 14:56:30 -04003786 current_locale, errors);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003787 if (res != 0) {
3788 if (res == -2) {
3789 PyObject *exc;
3790 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3791 "locale", str, len,
3792 (Py_ssize_t)wlen,
3793 (Py_ssize_t)(wlen + 1),
3794 reason);
3795 if (exc != NULL) {
3796 PyCodec_StrictErrors(exc);
3797 Py_DECREF(exc);
3798 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003799 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003800 else if (res == -3) {
3801 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3802 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003803 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003804 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003805 }
Victor Stinner2f197072011-12-17 07:08:30 +01003806 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003807 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003808
3809 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3810 PyMem_RawFree(wstr);
3811 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003812}
3813
3814PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003815PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3816 const char *errors)
3817{
Victor Stinner709d23d2019-05-02 14:56:30 -04003818 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3819 return unicode_decode_locale(str, len, error_handler, 1);
Victor Stinner2cba6b82018-01-10 22:46:15 +01003820}
3821
3822PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003823PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003824{
3825 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner709d23d2019-05-02 14:56:30 -04003826 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3827 return unicode_decode_locale(str, size, error_handler, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003828}
3829
3830
3831PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003832PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003833 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003834 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3835}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003836
Christian Heimes5894ba72007-11-04 11:43:14 +00003837PyObject*
3838PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3839{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003840 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnere2510952019-05-02 11:28:57 -04003841#ifdef _Py_FORCE_UTF8_FS_ENCODING
Victor Stinner709d23d2019-05-02 14:56:30 -04003842 if (interp->fs_codec.encoding) {
3843 return unicode_decode_utf8(s, size,
3844 interp->fs_codec.error_handler,
3845 interp->fs_codec.errors,
3846 NULL);
3847 }
3848 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02003849 const wchar_t *filesystem_errors = interp->config.filesystem_errors;
Victor Stinner709d23d2019-05-02 14:56:30 -04003850 _Py_error_handler errors;
Victor Stinner331a6a52019-05-27 16:39:22 +02003851 errors = get_error_handler_wide(filesystem_errors);
Victor Stinner709d23d2019-05-02 14:56:30 -04003852 assert(errors != _Py_ERROR_UNKNOWN);
3853 return unicode_decode_utf8(s, size, errors, NULL, NULL);
3854 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003855#else
Victor Stinner793b5312011-04-27 00:24:21 +02003856 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3857 cannot use it to encode and decode filenames before it is loaded. Load
3858 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003859 implementation of the locale codec until the codec registry is
Victor Stinner22eb6892019-06-26 00:51:05 +02003860 initialized and the Python codec is loaded.
3861 See _PyUnicode_InitEncodings(). */
Victor Stinner709d23d2019-05-02 14:56:30 -04003862 if (interp->fs_codec.encoding) {
Steve Dower78057b42016-11-06 19:35:08 -08003863 return PyUnicode_Decode(s, size,
Victor Stinner709d23d2019-05-02 14:56:30 -04003864 interp->fs_codec.encoding,
3865 interp->fs_codec.errors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003866 }
3867 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02003868 const wchar_t *filesystem_errors = interp->config.filesystem_errors;
Victor Stinner709d23d2019-05-02 14:56:30 -04003869 _Py_error_handler errors;
Victor Stinner331a6a52019-05-27 16:39:22 +02003870 errors = get_error_handler_wide(filesystem_errors);
Victor Stinner709d23d2019-05-02 14:56:30 -04003871 return unicode_decode_locale(s, size, errors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003872 }
Victor Stinnerad158722010-10-27 00:25:46 +00003873#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003874}
3875
Martin v. Löwis011e8422009-05-05 04:43:17 +00003876
3877int
3878PyUnicode_FSConverter(PyObject* arg, void* addr)
3879{
Brett Cannonec6ce872016-09-06 15:50:29 -07003880 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003881 PyObject *output = NULL;
3882 Py_ssize_t size;
3883 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003884 if (arg == NULL) {
3885 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003886 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003887 return 1;
3888 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003889 path = PyOS_FSPath(arg);
3890 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003891 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003892 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003893 if (PyBytes_Check(path)) {
3894 output = path;
3895 }
3896 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3897 output = PyUnicode_EncodeFSDefault(path);
3898 Py_DECREF(path);
3899 if (!output) {
3900 return 0;
3901 }
3902 assert(PyBytes_Check(output));
3903 }
3904
Victor Stinner0ea2a462010-04-30 00:22:08 +00003905 size = PyBytes_GET_SIZE(output);
3906 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003907 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003908 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003909 Py_DECREF(output);
3910 return 0;
3911 }
3912 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003913 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003914}
3915
3916
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003917int
3918PyUnicode_FSDecoder(PyObject* arg, void* addr)
3919{
Brett Cannona5711202016-09-06 19:36:01 -07003920 int is_buffer = 0;
3921 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003922 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003923 if (arg == NULL) {
3924 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003925 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003926 return 1;
3927 }
Brett Cannona5711202016-09-06 19:36:01 -07003928
3929 is_buffer = PyObject_CheckBuffer(arg);
3930 if (!is_buffer) {
3931 path = PyOS_FSPath(arg);
3932 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003933 return 0;
3934 }
Brett Cannona5711202016-09-06 19:36:01 -07003935 }
3936 else {
3937 path = arg;
3938 Py_INCREF(arg);
3939 }
3940
3941 if (PyUnicode_Check(path)) {
Brett Cannona5711202016-09-06 19:36:01 -07003942 output = path;
3943 }
3944 else if (PyBytes_Check(path) || is_buffer) {
3945 PyObject *path_bytes = NULL;
3946
3947 if (!PyBytes_Check(path) &&
3948 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Victor Stinner998b8062018-09-12 00:23:25 +02003949 "path should be string, bytes, or os.PathLike, not %.200s",
3950 Py_TYPE(arg)->tp_name)) {
3951 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003952 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003953 }
3954 path_bytes = PyBytes_FromObject(path);
3955 Py_DECREF(path);
3956 if (!path_bytes) {
3957 return 0;
3958 }
3959 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3960 PyBytes_GET_SIZE(path_bytes));
3961 Py_DECREF(path_bytes);
3962 if (!output) {
3963 return 0;
3964 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003965 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003966 else {
3967 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003968 "path should be string, bytes, or os.PathLike, not %.200s",
3969 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003970 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003971 return 0;
3972 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003973 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003974 Py_DECREF(output);
3975 return 0;
3976 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003977 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003978 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003979 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003980 Py_DECREF(output);
3981 return 0;
3982 }
3983 *(PyObject**)addr = output;
3984 return Py_CLEANUP_SUPPORTED;
3985}
3986
3987
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003988const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003989PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003990{
Christian Heimesf3863112007-11-22 07:46:41 +00003991 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003993 if (!PyUnicode_Check(unicode)) {
3994 PyErr_BadArgument();
3995 return NULL;
3996 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003997 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003998 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004000 if (PyUnicode_UTF8(unicode) == NULL) {
4001 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03004002 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003 if (bytes == NULL)
4004 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004005 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
4006 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01004007 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004008 Py_DECREF(bytes);
4009 return NULL;
4010 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004011 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02004012 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004013 PyBytes_AS_STRING(bytes),
4014 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015 Py_DECREF(bytes);
4016 }
4017
4018 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004019 *psize = PyUnicode_UTF8_LENGTH(unicode);
4020 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004021}
4022
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02004023const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004025{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004026 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4027}
4028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004029Py_UNICODE *
4030PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4031{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004032 if (!PyUnicode_Check(unicode)) {
4033 PyErr_BadArgument();
4034 return NULL;
4035 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03004036 Py_UNICODE *w = _PyUnicode_WSTR(unicode);
4037 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038 /* Non-ASCII compact unicode object */
Serhiy Storchakac46db922018-10-23 22:58:24 +03004039 assert(_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004040 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041
Serhiy Storchakac46db922018-10-23 22:58:24 +03004042 Py_ssize_t wlen = unicode_get_widechar_size(unicode);
4043 if ((size_t)wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4044 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004045 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004046 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03004047 w = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) * (wlen + 1));
4048 if (w == NULL) {
4049 PyErr_NoMemory();
4050 return NULL;
4051 }
4052 unicode_copy_as_widechar(unicode, w, wlen + 1);
4053 _PyUnicode_WSTR(unicode) = w;
4054 if (!PyUnicode_IS_COMPACT_ASCII(unicode)) {
4055 _PyUnicode_WSTR_LENGTH(unicode) = wlen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004056 }
4057 }
4058 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004059 *size = PyUnicode_WSTR_LENGTH(unicode);
Serhiy Storchakac46db922018-10-23 22:58:24 +03004060 return w;
Martin v. Löwis5b222132007-06-10 09:51:05 +00004061}
4062
Alexander Belopolsky40018472011-02-26 01:02:56 +00004063Py_UNICODE *
4064PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004065{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004066 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004067}
4068
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03004069const Py_UNICODE *
4070_PyUnicode_AsUnicode(PyObject *unicode)
4071{
4072 Py_ssize_t size;
4073 const Py_UNICODE *wstr;
4074
4075 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
4076 if (wstr && wcslen(wstr) != (size_t)size) {
4077 PyErr_SetString(PyExc_ValueError, "embedded null character");
4078 return NULL;
4079 }
4080 return wstr;
4081}
4082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004083
Alexander Belopolsky40018472011-02-26 01:02:56 +00004084Py_ssize_t
4085PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004086{
4087 if (!PyUnicode_Check(unicode)) {
4088 PyErr_BadArgument();
4089 goto onError;
4090 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004091 if (_PyUnicode_WSTR(unicode) == NULL) {
4092 if (PyUnicode_AsUnicode(unicode) == NULL)
4093 goto onError;
4094 }
4095 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004096
Benjamin Peterson29060642009-01-31 22:14:21 +00004097 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004098 return -1;
4099}
4100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004101Py_ssize_t
4102PyUnicode_GetLength(PyObject *unicode)
4103{
Victor Stinner07621332012-06-16 04:53:46 +02004104 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004105 PyErr_BadArgument();
4106 return -1;
4107 }
Victor Stinner07621332012-06-16 04:53:46 +02004108 if (PyUnicode_READY(unicode) == -1)
4109 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004110 return PyUnicode_GET_LENGTH(unicode);
4111}
4112
4113Py_UCS4
4114PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4115{
Victor Stinner69ed0f42013-04-09 21:48:24 +02004116 void *data;
4117 int kind;
4118
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004119 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004120 PyErr_BadArgument();
4121 return (Py_UCS4)-1;
4122 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004123 if (PyUnicode_READY(unicode) == -1) {
4124 return (Py_UCS4)-1;
4125 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004126 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004127 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004128 return (Py_UCS4)-1;
4129 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004130 data = PyUnicode_DATA(unicode);
4131 kind = PyUnicode_KIND(unicode);
4132 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004133}
4134
4135int
4136PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4137{
4138 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004139 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004140 return -1;
4141 }
Victor Stinner488fa492011-12-12 00:01:39 +01004142 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004143 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004144 PyErr_SetString(PyExc_IndexError, "string index out of range");
4145 return -1;
4146 }
Victor Stinner488fa492011-12-12 00:01:39 +01004147 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004148 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004149 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4150 PyErr_SetString(PyExc_ValueError, "character out of range");
4151 return -1;
4152 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004153 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4154 index, ch);
4155 return 0;
4156}
4157
Alexander Belopolsky40018472011-02-26 01:02:56 +00004158const char *
4159PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004160{
Victor Stinner42cb4622010-09-01 19:39:01 +00004161 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004162}
4163
Victor Stinner554f3f02010-06-16 23:33:54 +00004164/* create or adjust a UnicodeDecodeError */
4165static void
4166make_decode_exception(PyObject **exceptionObject,
4167 const char *encoding,
4168 const char *input, Py_ssize_t length,
4169 Py_ssize_t startpos, Py_ssize_t endpos,
4170 const char *reason)
4171{
4172 if (*exceptionObject == NULL) {
4173 *exceptionObject = PyUnicodeDecodeError_Create(
4174 encoding, input, length, startpos, endpos, reason);
4175 }
4176 else {
4177 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4178 goto onError;
4179 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4180 goto onError;
4181 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4182 goto onError;
4183 }
4184 return;
4185
4186onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004187 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004188}
4189
Steve Dowercc16be82016-09-08 10:35:16 -07004190#ifdef MS_WINDOWS
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004191static int
4192widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
4193{
4194 if (newsize > *size) {
4195 wchar_t *newbuf = *buf;
4196 if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
4197 PyErr_NoMemory();
4198 return -1;
4199 }
4200 *buf = newbuf;
4201 }
4202 *size = newsize;
4203 return 0;
4204}
4205
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004206/* error handling callback helper:
4207 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004208 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004209 and adjust various state variables.
4210 return 0 on success, -1 on error
4211*/
4212
Alexander Belopolsky40018472011-02-26 01:02:56 +00004213static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004214unicode_decode_call_errorhandler_wchar(
4215 const char *errors, PyObject **errorHandler,
4216 const char *encoding, const char *reason,
4217 const char **input, const char **inend, Py_ssize_t *startinpos,
4218 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004219 wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004220{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004221 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004222
4223 PyObject *restuple = NULL;
4224 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004225 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004226 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004227 Py_ssize_t requiredsize;
4228 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004229 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004230 wchar_t *repwstr;
4231 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004232
4233 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004234 *errorHandler = PyCodec_LookupError(errors);
4235 if (*errorHandler == NULL)
4236 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004237 }
4238
Victor Stinner554f3f02010-06-16 23:33:54 +00004239 make_decode_exception(exceptionObject,
4240 encoding,
4241 *input, *inend - *input,
4242 *startinpos, *endinpos,
4243 reason);
4244 if (*exceptionObject == NULL)
4245 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004246
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004247 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004248 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004249 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004250 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004251 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004252 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004253 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004254 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004255 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004256
4257 /* Copy back the bytes variables, which might have been modified by the
4258 callback */
4259 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4260 if (!inputobj)
4261 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004262 *input = PyBytes_AS_STRING(inputobj);
4263 insize = PyBytes_GET_SIZE(inputobj);
4264 *inend = *input + insize;
4265 /* we can DECREF safely, as the exception has another reference,
4266 so the object won't go away. */
4267 Py_DECREF(inputobj);
4268
4269 if (newpos<0)
4270 newpos = insize+newpos;
4271 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004272 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004273 goto onError;
4274 }
4275
4276 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4277 if (repwstr == NULL)
4278 goto onError;
4279 /* need more space? (at least enough for what we
4280 have+the replacement+the rest of the string (starting
4281 at the new input position), so we won't have to check space
4282 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004283 requiredsize = *outpos;
4284 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4285 goto overflow;
4286 requiredsize += repwlen;
4287 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4288 goto overflow;
4289 requiredsize += insize - newpos;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004290 outsize = *bufsize;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004291 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004292 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004293 requiredsize = 2*outsize;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004294 if (widechar_resize(buf, bufsize, requiredsize) < 0) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004295 goto onError;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004296 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004297 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004298 wcsncpy(*buf + *outpos, repwstr, repwlen);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004299 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004300 *endinpos = newpos;
4301 *inptr = *input + newpos;
4302
4303 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004304 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004305 return 0;
4306
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004307 overflow:
4308 PyErr_SetString(PyExc_OverflowError,
4309 "decoded result is too long for a Python string");
4310
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004311 onError:
4312 Py_XDECREF(restuple);
4313 return -1;
4314}
Steve Dowercc16be82016-09-08 10:35:16 -07004315#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004316
4317static int
4318unicode_decode_call_errorhandler_writer(
4319 const char *errors, PyObject **errorHandler,
4320 const char *encoding, const char *reason,
4321 const char **input, const char **inend, Py_ssize_t *startinpos,
4322 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4323 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4324{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004325 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004326
4327 PyObject *restuple = NULL;
4328 PyObject *repunicode = NULL;
4329 Py_ssize_t insize;
4330 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004331 Py_ssize_t replen;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004332 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004333 PyObject *inputobj = NULL;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004334 int need_to_grow = 0;
4335 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004336
4337 if (*errorHandler == NULL) {
4338 *errorHandler = PyCodec_LookupError(errors);
4339 if (*errorHandler == NULL)
4340 goto onError;
4341 }
4342
4343 make_decode_exception(exceptionObject,
4344 encoding,
4345 *input, *inend - *input,
4346 *startinpos, *endinpos,
4347 reason);
4348 if (*exceptionObject == NULL)
4349 goto onError;
4350
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004351 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004352 if (restuple == NULL)
4353 goto onError;
4354 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004355 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004356 goto onError;
4357 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004358 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004359 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004360
4361 /* Copy back the bytes variables, which might have been modified by the
4362 callback */
4363 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4364 if (!inputobj)
4365 goto onError;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004366 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004367 *input = PyBytes_AS_STRING(inputobj);
4368 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004369 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004370 /* we can DECREF safely, as the exception has another reference,
4371 so the object won't go away. */
4372 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004373
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004374 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004375 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004376 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004377 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004378 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004379 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004380
Victor Stinner170ca6f2013-04-18 00:25:28 +02004381 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004382 if (replen > 1) {
4383 writer->min_length += replen - 1;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004384 need_to_grow = 1;
4385 }
4386 new_inptr = *input + newpos;
4387 if (*inend - new_inptr > remain) {
4388 /* We don't know the decoding algorithm here so we make the worst
4389 assumption that one byte decodes to one unicode character.
4390 If unfortunately one byte could decode to more unicode characters,
4391 the decoder may write out-of-bound then. Is it possible for the
4392 algorithms using this function? */
4393 writer->min_length += *inend - new_inptr - remain;
4394 need_to_grow = 1;
4395 }
4396 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004397 writer->overallocate = 1;
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02004398 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004399 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4400 goto onError;
4401 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004402 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004403 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004405 *endinpos = newpos;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004406 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004407
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004408 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004409 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004410 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004411
Benjamin Peterson29060642009-01-31 22:14:21 +00004412 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004413 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004414 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004415}
4416
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004417/* --- UTF-7 Codec -------------------------------------------------------- */
4418
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419/* See RFC2152 for details. We encode conservatively and decode liberally. */
4420
4421/* Three simple macros defining base-64. */
4422
4423/* Is c a base-64 character? */
4424
4425#define IS_BASE64(c) \
4426 (((c) >= 'A' && (c) <= 'Z') || \
4427 ((c) >= 'a' && (c) <= 'z') || \
4428 ((c) >= '0' && (c) <= '9') || \
4429 (c) == '+' || (c) == '/')
4430
4431/* given that c is a base-64 character, what is its base-64 value? */
4432
4433#define FROM_BASE64(c) \
4434 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4435 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4436 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4437 (c) == '+' ? 62 : 63)
4438
4439/* What is the base-64 character of the bottom 6 bits of n? */
4440
4441#define TO_BASE64(n) \
4442 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4443
4444/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4445 * decoded as itself. We are permissive on decoding; the only ASCII
4446 * byte not decoding to itself is the + which begins a base64
4447 * string. */
4448
4449#define DECODE_DIRECT(c) \
4450 ((c) <= 127 && (c) != '+')
4451
4452/* The UTF-7 encoder treats ASCII characters differently according to
4453 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4454 * the above). See RFC2152. This array identifies these different
4455 * sets:
4456 * 0 : "Set D"
4457 * alphanumeric and '(),-./:?
4458 * 1 : "Set O"
4459 * !"#$%&*;<=>@[]^_`{|}
4460 * 2 : "whitespace"
4461 * ht nl cr sp
4462 * 3 : special (must be base64 encoded)
4463 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4464 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004465
Tim Petersced69f82003-09-16 20:30:58 +00004466static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467char utf7_category[128] = {
4468/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4469 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4470/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4471 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4472/* sp ! " # $ % & ' ( ) * + , - . / */
4473 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4474/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4475 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4476/* @ A B C D E F G H I J K L M N O */
4477 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4478/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4479 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4480/* ` a b c d e f g h i j k l m n o */
4481 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4482/* p q r s t u v w x y z { | } ~ del */
4483 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004484};
4485
Antoine Pitrou244651a2009-05-04 18:56:13 +00004486/* ENCODE_DIRECT: this character should be encoded as itself. The
4487 * answer depends on whether we are encoding set O as itself, and also
4488 * on whether we are encoding whitespace as itself. RFC2152 makes it
4489 * clear that the answers to these questions vary between
4490 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004491
Antoine Pitrou244651a2009-05-04 18:56:13 +00004492#define ENCODE_DIRECT(c, directO, directWS) \
4493 ((c) < 128 && (c) > 0 && \
4494 ((utf7_category[(c)] == 0) || \
4495 (directWS && (utf7_category[(c)] == 2)) || \
4496 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497
Alexander Belopolsky40018472011-02-26 01:02:56 +00004498PyObject *
4499PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004500 Py_ssize_t size,
4501 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004502{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004503 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4504}
4505
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506/* The decoder. The only state we preserve is our read position,
4507 * i.e. how many characters we have consumed. So if we end in the
4508 * middle of a shift sequence we have to back off the read position
4509 * and the output to the beginning of the sequence, otherwise we lose
4510 * all the shift state (seen bits, number of bits seen, high
4511 * surrogate). */
4512
Alexander Belopolsky40018472011-02-26 01:02:56 +00004513PyObject *
4514PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004515 Py_ssize_t size,
4516 const char *errors,
4517 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004518{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004519 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004520 Py_ssize_t startinpos;
4521 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004522 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004523 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524 const char *errmsg = "";
4525 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004526 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527 unsigned int base64bits = 0;
4528 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004529 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004530 PyObject *errorHandler = NULL;
4531 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004532
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004533 if (size == 0) {
4534 if (consumed)
4535 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004536 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004537 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004538
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004539 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004540 _PyUnicodeWriter_Init(&writer);
4541 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004542
4543 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004544 e = s + size;
4545
4546 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004547 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004548 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004549 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004550
Antoine Pitrou244651a2009-05-04 18:56:13 +00004551 if (inShift) { /* in a base-64 section */
4552 if (IS_BASE64(ch)) { /* consume a base-64 character */
4553 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4554 base64bits += 6;
4555 s++;
4556 if (base64bits >= 16) {
4557 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004558 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004559 base64bits -= 16;
4560 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004561 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004562 if (surrogate) {
4563 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004564 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4565 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004566 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004567 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004568 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004569 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004570 }
4571 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004572 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004573 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004574 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 }
4576 }
Victor Stinner551ac952011-11-29 22:58:13 +01004577 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 /* first surrogate */
4579 surrogate = outCh;
4580 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004581 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004582 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004583 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004584 }
4585 }
4586 }
4587 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004588 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004589 if (base64bits > 0) { /* left-over bits */
4590 if (base64bits >= 6) {
4591 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004592 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004593 errmsg = "partial character in shift sequence";
4594 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004595 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004596 else {
4597 /* Some bits remain; they should be zero */
4598 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004599 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004600 errmsg = "non-zero padding bits in shift sequence";
4601 goto utf7Error;
4602 }
4603 }
4604 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004605 if (surrogate && DECODE_DIRECT(ch)) {
4606 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4607 goto onError;
4608 }
4609 surrogate = 0;
4610 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004611 /* '-' is absorbed; other terminating
4612 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004613 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004614 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004615 }
4616 }
4617 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004618 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004619 s++; /* consume '+' */
4620 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004621 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004622 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004623 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004624 }
Zackery Spytze349bf22018-08-18 22:43:38 -06004625 else if (s < e && !IS_BASE64(*s)) {
4626 s++;
4627 errmsg = "ill-formed sequence";
4628 goto utf7Error;
4629 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004630 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004631 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004632 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004633 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004634 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004635 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004636 }
4637 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004638 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004639 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004640 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004641 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004642 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004643 else {
4644 startinpos = s-starts;
4645 s++;
4646 errmsg = "unexpected special character";
4647 goto utf7Error;
4648 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004649 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004650utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004651 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004652 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004653 errors, &errorHandler,
4654 "utf7", errmsg,
4655 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004656 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004657 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004658 }
4659
Antoine Pitrou244651a2009-05-04 18:56:13 +00004660 /* end of string */
4661
4662 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4663 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004664 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004665 if (surrogate ||
4666 (base64bits >= 6) ||
4667 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004668 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004669 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004670 errors, &errorHandler,
4671 "utf7", "unterminated shift sequence",
4672 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004673 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004674 goto onError;
4675 if (s < e)
4676 goto restart;
4677 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004678 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004679
4680 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004681 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004682 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004683 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004684 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004685 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004686 writer.kind, writer.data, shiftOutStart);
4687 Py_XDECREF(errorHandler);
4688 Py_XDECREF(exc);
4689 _PyUnicodeWriter_Dealloc(&writer);
4690 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004691 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004692 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004693 }
4694 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004695 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004696 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004697 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004698
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004699 Py_XDECREF(errorHandler);
4700 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004701 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004702
Benjamin Peterson29060642009-01-31 22:14:21 +00004703 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004704 Py_XDECREF(errorHandler);
4705 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004706 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004707 return NULL;
4708}
4709
4710
Alexander Belopolsky40018472011-02-26 01:02:56 +00004711PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004712_PyUnicode_EncodeUTF7(PyObject *str,
4713 int base64SetO,
4714 int base64WhiteSpace,
4715 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004716{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004717 int kind;
4718 void *data;
4719 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004720 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004721 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004722 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004723 unsigned int base64bits = 0;
4724 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004725 char * out;
4726 char * start;
4727
Benjamin Petersonbac79492012-01-14 13:34:47 -05004728 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004729 return NULL;
4730 kind = PyUnicode_KIND(str);
4731 data = PyUnicode_DATA(str);
4732 len = PyUnicode_GET_LENGTH(str);
4733
4734 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004735 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004736
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004737 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004738 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004739 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004740 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004741 if (v == NULL)
4742 return NULL;
4743
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004744 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004745 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004746 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004747
Antoine Pitrou244651a2009-05-04 18:56:13 +00004748 if (inShift) {
4749 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4750 /* shifting out */
4751 if (base64bits) { /* output remaining bits */
4752 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4753 base64buffer = 0;
4754 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004755 }
4756 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004757 /* Characters not in the BASE64 set implicitly unshift the sequence
4758 so no '-' is required, except if the character is itself a '-' */
4759 if (IS_BASE64(ch) || ch == '-') {
4760 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004761 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004762 *out++ = (char) ch;
4763 }
4764 else {
4765 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004766 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004767 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004768 else { /* not in a shift sequence */
4769 if (ch == '+') {
4770 *out++ = '+';
4771 *out++ = '-';
4772 }
4773 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4774 *out++ = (char) ch;
4775 }
4776 else {
4777 *out++ = '+';
4778 inShift = 1;
4779 goto encode_char;
4780 }
4781 }
4782 continue;
4783encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004784 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004785 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004786
Antoine Pitrou244651a2009-05-04 18:56:13 +00004787 /* code first surrogate */
4788 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004789 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004790 while (base64bits >= 6) {
4791 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4792 base64bits -= 6;
4793 }
4794 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004795 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004796 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004797 base64bits += 16;
4798 base64buffer = (base64buffer << 16) | ch;
4799 while (base64bits >= 6) {
4800 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4801 base64bits -= 6;
4802 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004803 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004804 if (base64bits)
4805 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4806 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004807 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004808 if (_PyBytes_Resize(&v, out - start) < 0)
4809 return NULL;
4810 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004811}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004812PyObject *
4813PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4814 Py_ssize_t size,
4815 int base64SetO,
4816 int base64WhiteSpace,
4817 const char *errors)
4818{
4819 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004820 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004821 if (tmp == NULL)
4822 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004823 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004824 base64WhiteSpace, errors);
4825 Py_DECREF(tmp);
4826 return result;
4827}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004828
Antoine Pitrou244651a2009-05-04 18:56:13 +00004829#undef IS_BASE64
4830#undef FROM_BASE64
4831#undef TO_BASE64
4832#undef DECODE_DIRECT
4833#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004834
Guido van Rossumd57fd912000-03-10 22:53:23 +00004835/* --- UTF-8 Codec -------------------------------------------------------- */
4836
Alexander Belopolsky40018472011-02-26 01:02:56 +00004837PyObject *
4838PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004839 Py_ssize_t size,
4840 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004841{
Walter Dörwald69652032004-09-07 20:24:22 +00004842 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4843}
4844
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004845#include "stringlib/asciilib.h"
4846#include "stringlib/codecs.h"
4847#include "stringlib/undef.h"
4848
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004849#include "stringlib/ucs1lib.h"
4850#include "stringlib/codecs.h"
4851#include "stringlib/undef.h"
4852
4853#include "stringlib/ucs2lib.h"
4854#include "stringlib/codecs.h"
4855#include "stringlib/undef.h"
4856
4857#include "stringlib/ucs4lib.h"
4858#include "stringlib/codecs.h"
4859#include "stringlib/undef.h"
4860
Antoine Pitrouab868312009-01-10 15:40:25 +00004861/* Mask to quickly check whether a C 'long' contains a
4862 non-ASCII, UTF8-encoded char. */
4863#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004864# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004865#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004866# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004867#else
4868# error C 'long' size should be either 4 or 8!
4869#endif
4870
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004871static Py_ssize_t
4872ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004873{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004874 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004875 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004876
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004877 /*
4878 * Issue #17237: m68k is a bit different from most architectures in
4879 * that objects do not use "natural alignment" - for example, int and
4880 * long are only aligned at 2-byte boundaries. Therefore the assert()
4881 * won't work; also, tests have shown that skipping the "optimised
4882 * version" will even speed up m68k.
4883 */
4884#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004885#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004886 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4887 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004888 /* Fast path, see in STRINGLIB(utf8_decode) for
4889 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004890 /* Help allocation */
4891 const char *_p = p;
4892 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004893 while (_p < aligned_end) {
4894 unsigned long value = *(const unsigned long *) _p;
4895 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004896 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004897 *((unsigned long *)q) = value;
4898 _p += SIZEOF_LONG;
4899 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004900 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004901 p = _p;
4902 while (p < end) {
4903 if ((unsigned char)*p & 0x80)
4904 break;
4905 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004906 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004907 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004908 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004909#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004910#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911 while (p < end) {
4912 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4913 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004914 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004915 /* Help allocation */
4916 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004917 while (_p < aligned_end) {
4918 unsigned long value = *(unsigned long *) _p;
4919 if (value & ASCII_CHAR_MASK)
4920 break;
4921 _p += SIZEOF_LONG;
4922 }
4923 p = _p;
4924 if (_p == end)
4925 break;
4926 }
4927 if ((unsigned char)*p & 0x80)
4928 break;
4929 ++p;
4930 }
4931 memcpy(dest, start, p - start);
4932 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004933}
Antoine Pitrouab868312009-01-10 15:40:25 +00004934
Victor Stinner709d23d2019-05-02 14:56:30 -04004935static PyObject *
4936unicode_decode_utf8(const char *s, Py_ssize_t size,
4937 _Py_error_handler error_handler, const char *errors,
4938 Py_ssize_t *consumed)
Victor Stinner785938e2011-12-11 20:09:03 +01004939{
Victor Stinner785938e2011-12-11 20:09:03 +01004940 if (size == 0) {
4941 if (consumed)
4942 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004943 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004944 }
4945
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004946 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4947 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004948 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004949 *consumed = 1;
4950 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004951 }
4952
Inada Naoki770847a2019-06-24 12:30:24 +09004953 const char *starts = s;
4954 const char *end = s + size;
Victor Stinner785938e2011-12-11 20:09:03 +01004955
Inada Naoki770847a2019-06-24 12:30:24 +09004956 // fast path: try ASCII string.
4957 PyObject *u = PyUnicode_New(size, 127);
4958 if (u == NULL) {
4959 return NULL;
4960 }
4961 s += ascii_decode(s, end, PyUnicode_DATA(u));
4962 if (s == end) {
4963 return u;
4964 }
4965
4966 // Use _PyUnicodeWriter after fast path is failed.
4967 _PyUnicodeWriter writer;
4968 _PyUnicodeWriter_InitWithBuffer(&writer, u);
4969 writer.pos = s - starts;
4970
4971 Py_ssize_t startinpos, endinpos;
4972 const char *errmsg = "";
4973 PyObject *error_handler_obj = NULL;
4974 PyObject *exc = NULL;
4975
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004976 while (s < end) {
4977 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004978 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004979
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004980 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004981 if (PyUnicode_IS_ASCII(writer.buffer))
4982 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004983 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004984 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004985 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004986 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004987 } else {
4988 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004989 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004990 }
4991
4992 switch (ch) {
4993 case 0:
4994 if (s == end || consumed)
4995 goto End;
4996 errmsg = "unexpected end of data";
4997 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004998 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004999 break;
5000 case 1:
5001 errmsg = "invalid start byte";
5002 startinpos = s - starts;
5003 endinpos = startinpos + 1;
5004 break;
5005 case 2:
Serhiy Storchaka894263b2019-06-25 11:54:18 +03005006 if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
5007 && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
5008 {
5009 /* Truncated surrogate code in range D800-DFFF */
Serhiy Storchaka7a465cb2019-03-30 08:23:38 +02005010 goto End;
5011 }
Serhiy Storchaka894263b2019-06-25 11:54:18 +03005012 /* fall through */
5013 case 3:
5014 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005015 errmsg = "invalid continuation byte";
5016 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005017 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005018 break;
5019 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005020 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005021 goto onError;
5022 continue;
5023 }
5024
Victor Stinner1d65d912015-10-05 13:43:50 +02005025 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02005026 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner1d65d912015-10-05 13:43:50 +02005027
5028 switch (error_handler) {
5029 case _Py_ERROR_IGNORE:
5030 s += (endinpos - startinpos);
5031 break;
5032
5033 case _Py_ERROR_REPLACE:
5034 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5035 goto onError;
5036 s += (endinpos - startinpos);
5037 break;
5038
5039 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005040 {
5041 Py_ssize_t i;
5042
Victor Stinner1d65d912015-10-05 13:43:50 +02005043 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5044 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005045 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005046 ch = (Py_UCS4)(unsigned char)(starts[i]);
5047 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5048 ch + 0xdc00);
5049 writer.pos++;
5050 }
5051 s += (endinpos - startinpos);
5052 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005053 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005054
5055 default:
5056 if (unicode_decode_call_errorhandler_writer(
5057 errors, &error_handler_obj,
5058 "utf-8", errmsg,
5059 &starts, &end, &startinpos, &endinpos, &exc, &s,
5060 &writer))
5061 goto onError;
5062 }
Victor Stinner785938e2011-12-11 20:09:03 +01005063 }
5064
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005065End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005066 if (consumed)
5067 *consumed = s - starts;
5068
Victor Stinner1d65d912015-10-05 13:43:50 +02005069 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005070 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005071 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005072
5073onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005074 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005075 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005076 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005077 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005078}
5079
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005080
Victor Stinner709d23d2019-05-02 14:56:30 -04005081PyObject *
5082PyUnicode_DecodeUTF8Stateful(const char *s,
5083 Py_ssize_t size,
5084 const char *errors,
5085 Py_ssize_t *consumed)
5086{
5087 return unicode_decode_utf8(s, size, _Py_ERROR_UNKNOWN, errors, consumed);
5088}
5089
5090
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005091/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
5092 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005093
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005094 On success, write a pointer to a newly allocated wide character string into
5095 *wstr (use PyMem_RawFree() to free the memory) and write the output length
5096 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005097
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005098 On memory allocation failure, return -1.
5099
5100 On decoding error (if surrogateescape is zero), return -2. If wlen is
5101 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
5102 is not NULL, write the decoding error message into *reason. */
5103int
5104_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005105 const char **reason, _Py_error_handler errors)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005106{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005107 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005108 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005109 wchar_t *unicode;
5110 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005111
Victor Stinner3d4226a2018-08-29 22:21:32 +02005112 int surrogateescape = 0;
5113 int surrogatepass = 0;
5114 switch (errors)
5115 {
5116 case _Py_ERROR_STRICT:
5117 break;
5118 case _Py_ERROR_SURROGATEESCAPE:
5119 surrogateescape = 1;
5120 break;
5121 case _Py_ERROR_SURROGATEPASS:
5122 surrogatepass = 1;
5123 break;
5124 default:
5125 return -3;
5126 }
5127
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005128 /* Note: size will always be longer than the resulting Unicode
5129 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01005130 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005131 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01005132 }
5133
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005134 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01005135 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005136 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01005137 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005138
5139 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005140 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005141 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005142 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005143 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005144#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005145 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005146#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005147 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005148#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005149 if (ch > 0xFF) {
5150#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005151 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005152#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005153 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005154 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005155 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5156 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5157#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005158 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005159 else {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005160 if (!ch && s == e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005161 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005162 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005163
5164 if (surrogateescape) {
5165 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5166 }
5167 else {
5168 /* Is it a valid three-byte code? */
5169 if (surrogatepass
5170 && (e - s) >= 3
5171 && (s[0] & 0xf0) == 0xe0
5172 && (s[1] & 0xc0) == 0x80
5173 && (s[2] & 0xc0) == 0x80)
5174 {
5175 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5176 s += 3;
5177 unicode[outpos++] = ch;
5178 }
5179 else {
5180 PyMem_RawFree(unicode );
5181 if (reason != NULL) {
5182 switch (ch) {
5183 case 0:
5184 *reason = "unexpected end of data";
5185 break;
5186 case 1:
5187 *reason = "invalid start byte";
5188 break;
5189 /* 2, 3, 4 */
5190 default:
5191 *reason = "invalid continuation byte";
5192 break;
5193 }
5194 }
5195 if (wlen != NULL) {
5196 *wlen = s - orig_s;
5197 }
5198 return -2;
5199 }
5200 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005201 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005202 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005203 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005204 if (wlen) {
5205 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005206 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005207 *wstr = unicode;
5208 return 0;
5209}
5210
Victor Stinner5f9cf232019-03-19 01:46:25 +01005211
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005212wchar_t*
Victor Stinner5f9cf232019-03-19 01:46:25 +01005213_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
5214 size_t *wlen)
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005215{
5216 wchar_t *wstr;
Victor Stinner5f9cf232019-03-19 01:46:25 +01005217 int res = _Py_DecodeUTF8Ex(arg, arglen,
5218 &wstr, wlen,
5219 NULL, _Py_ERROR_SURROGATEESCAPE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005220 if (res != 0) {
Victor Stinner5f9cf232019-03-19 01:46:25 +01005221 /* _Py_DecodeUTF8Ex() must support _Py_ERROR_SURROGATEESCAPE */
5222 assert(res != -3);
5223 if (wlen) {
5224 *wlen = (size_t)res;
5225 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005226 return NULL;
5227 }
5228 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005229}
5230
Antoine Pitrouab868312009-01-10 15:40:25 +00005231
Victor Stinnere47e6982017-12-21 15:45:16 +01005232/* UTF-8 encoder using the surrogateescape error handler .
5233
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005234 On success, return 0 and write the newly allocated character string (use
5235 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005236
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005237 On encoding failure, return -2 and write the position of the invalid
5238 surrogate character into *error_pos (if error_pos is set) and the decoding
5239 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005240
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005241 On memory allocation failure, return -1. */
5242int
5243_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005244 const char **reason, int raw_malloc, _Py_error_handler errors)
Victor Stinnere47e6982017-12-21 15:45:16 +01005245{
5246 const Py_ssize_t max_char_size = 4;
5247 Py_ssize_t len = wcslen(text);
5248
5249 assert(len >= 0);
5250
Victor Stinner3d4226a2018-08-29 22:21:32 +02005251 int surrogateescape = 0;
5252 int surrogatepass = 0;
5253 switch (errors)
5254 {
5255 case _Py_ERROR_STRICT:
5256 break;
5257 case _Py_ERROR_SURROGATEESCAPE:
5258 surrogateescape = 1;
5259 break;
5260 case _Py_ERROR_SURROGATEPASS:
5261 surrogatepass = 1;
5262 break;
5263 default:
5264 return -3;
5265 }
5266
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005267 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5268 return -1;
5269 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005270 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005271 if (raw_malloc) {
5272 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005273 }
5274 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005275 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005276 }
5277 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005278 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005279 }
5280
5281 char *p = bytes;
5282 Py_ssize_t i;
Victor Stinner3d4226a2018-08-29 22:21:32 +02005283 for (i = 0; i < len; ) {
5284 Py_ssize_t ch_pos = i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005285 Py_UCS4 ch = text[i];
Victor Stinner3d4226a2018-08-29 22:21:32 +02005286 i++;
5287#if Py_UNICODE_SIZE == 2
5288 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
5289 && i < len
5290 && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5291 {
5292 ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5293 i++;
5294 }
5295#endif
Victor Stinnere47e6982017-12-21 15:45:16 +01005296
5297 if (ch < 0x80) {
5298 /* Encode ASCII */
5299 *p++ = (char) ch;
5300
5301 }
5302 else if (ch < 0x0800) {
5303 /* Encode Latin-1 */
5304 *p++ = (char)(0xc0 | (ch >> 6));
5305 *p++ = (char)(0x80 | (ch & 0x3f));
5306 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005307 else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005308 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005309 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005310 if (error_pos != NULL) {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005311 *error_pos = (size_t)ch_pos;
Victor Stinnere47e6982017-12-21 15:45:16 +01005312 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005313 if (reason != NULL) {
5314 *reason = "encoding error";
5315 }
5316 if (raw_malloc) {
5317 PyMem_RawFree(bytes);
5318 }
5319 else {
5320 PyMem_Free(bytes);
5321 }
5322 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005323 }
5324 *p++ = (char)(ch & 0xff);
5325 }
5326 else if (ch < 0x10000) {
5327 *p++ = (char)(0xe0 | (ch >> 12));
5328 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5329 *p++ = (char)(0x80 | (ch & 0x3f));
5330 }
5331 else { /* ch >= 0x10000 */
5332 assert(ch <= MAX_UNICODE);
5333 /* Encode UCS4 Unicode ordinals */
5334 *p++ = (char)(0xf0 | (ch >> 18));
5335 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5336 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5337 *p++ = (char)(0x80 | (ch & 0x3f));
5338 }
5339 }
5340 *p++ = '\0';
5341
5342 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005343 char *bytes2;
5344 if (raw_malloc) {
5345 bytes2 = PyMem_RawRealloc(bytes, final_size);
5346 }
5347 else {
5348 bytes2 = PyMem_Realloc(bytes, final_size);
5349 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005350 if (bytes2 == NULL) {
5351 if (error_pos != NULL) {
5352 *error_pos = (size_t)-1;
5353 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005354 if (raw_malloc) {
5355 PyMem_RawFree(bytes);
5356 }
5357 else {
5358 PyMem_Free(bytes);
5359 }
5360 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005361 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005362 *str = bytes2;
5363 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005364}
5365
5366
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005367/* Primary internal function which creates utf8 encoded bytes objects.
5368
5369 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005370 and allocate exactly as much space needed at the end. Else allocate the
5371 maximum possible needed (4 result bytes per Unicode character), and return
5372 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005373*/
Victor Stinner709d23d2019-05-02 14:56:30 -04005374static PyObject *
5375unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
5376 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005377{
Victor Stinner6099a032011-12-18 14:22:26 +01005378 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005379 void *data;
5380 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005382 if (!PyUnicode_Check(unicode)) {
5383 PyErr_BadArgument();
5384 return NULL;
5385 }
5386
5387 if (PyUnicode_READY(unicode) == -1)
5388 return NULL;
5389
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005390 if (PyUnicode_UTF8(unicode))
5391 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5392 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005393
5394 kind = PyUnicode_KIND(unicode);
5395 data = PyUnicode_DATA(unicode);
5396 size = PyUnicode_GET_LENGTH(unicode);
5397
Benjamin Petersonead6b532011-12-20 17:23:42 -06005398 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005399 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005400 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005401 case PyUnicode_1BYTE_KIND:
5402 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5403 assert(!PyUnicode_IS_ASCII(unicode));
Victor Stinner709d23d2019-05-02 14:56:30 -04005404 return ucs1lib_utf8_encoder(unicode, data, size, error_handler, errors);
Victor Stinner6099a032011-12-18 14:22:26 +01005405 case PyUnicode_2BYTE_KIND:
Victor Stinner709d23d2019-05-02 14:56:30 -04005406 return ucs2lib_utf8_encoder(unicode, data, size, error_handler, errors);
Victor Stinner6099a032011-12-18 14:22:26 +01005407 case PyUnicode_4BYTE_KIND:
Victor Stinner709d23d2019-05-02 14:56:30 -04005408 return ucs4lib_utf8_encoder(unicode, data, size, error_handler, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005409 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005410}
5411
Alexander Belopolsky40018472011-02-26 01:02:56 +00005412PyObject *
Victor Stinner709d23d2019-05-02 14:56:30 -04005413_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5414{
5415 return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5416}
5417
5418
5419PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005420PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5421 Py_ssize_t size,
5422 const char *errors)
5423{
5424 PyObject *v, *unicode;
5425
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005426 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005427 if (unicode == NULL)
5428 return NULL;
5429 v = _PyUnicode_AsUTF8String(unicode, errors);
5430 Py_DECREF(unicode);
5431 return v;
5432}
5433
5434PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005435PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005437 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005438}
5439
Walter Dörwald41980ca2007-08-16 21:55:45 +00005440/* --- UTF-32 Codec ------------------------------------------------------- */
5441
5442PyObject *
5443PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005444 Py_ssize_t size,
5445 const char *errors,
5446 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005447{
5448 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5449}
5450
5451PyObject *
5452PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005453 Py_ssize_t size,
5454 const char *errors,
5455 int *byteorder,
5456 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005457{
5458 const char *starts = s;
5459 Py_ssize_t startinpos;
5460 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005461 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005462 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005463 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005464 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005465 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005466 PyObject *errorHandler = NULL;
5467 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005468
Walter Dörwald41980ca2007-08-16 21:55:45 +00005469 q = (unsigned char *)s;
5470 e = q + size;
5471
5472 if (byteorder)
5473 bo = *byteorder;
5474
5475 /* Check for BOM marks (U+FEFF) in the input and adjust current
5476 byte order setting accordingly. In native mode, the leading BOM
5477 mark is skipped, in all other modes, it is copied to the output
5478 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005479 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005480 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005481 if (bom == 0x0000FEFF) {
5482 bo = -1;
5483 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005484 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005485 else if (bom == 0xFFFE0000) {
5486 bo = 1;
5487 q += 4;
5488 }
5489 if (byteorder)
5490 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005491 }
5492
Victor Stinnere64322e2012-10-30 23:12:47 +01005493 if (q == e) {
5494 if (consumed)
5495 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005496 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005497 }
5498
Victor Stinnere64322e2012-10-30 23:12:47 +01005499#ifdef WORDS_BIGENDIAN
5500 le = bo < 0;
5501#else
5502 le = bo <= 0;
5503#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005504 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005505
Victor Stinner8f674cc2013-04-17 23:02:17 +02005506 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005507 writer.min_length = (e - q + 3) / 4;
5508 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005509 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005510
Victor Stinnere64322e2012-10-30 23:12:47 +01005511 while (1) {
5512 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005513 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005514
Victor Stinnere64322e2012-10-30 23:12:47 +01005515 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005516 enum PyUnicode_Kind kind = writer.kind;
5517 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005518 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005519 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005520 if (le) {
5521 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005522 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005523 if (ch > maxch)
5524 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005525 if (kind != PyUnicode_1BYTE_KIND &&
5526 Py_UNICODE_IS_SURROGATE(ch))
5527 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005528 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005529 q += 4;
5530 } while (q <= last);
5531 }
5532 else {
5533 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005534 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005535 if (ch > maxch)
5536 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005537 if (kind != PyUnicode_1BYTE_KIND &&
5538 Py_UNICODE_IS_SURROGATE(ch))
5539 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005540 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005541 q += 4;
5542 } while (q <= last);
5543 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005544 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005545 }
5546
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005547 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005548 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005549 startinpos = ((const char *)q) - starts;
5550 endinpos = startinpos + 4;
5551 }
5552 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005553 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005554 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005555 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005556 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005557 startinpos = ((const char *)q) - starts;
5558 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005559 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005560 else {
5561 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005562 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005563 goto onError;
5564 q += 4;
5565 continue;
5566 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005567 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005568 startinpos = ((const char *)q) - starts;
5569 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005570 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005571
5572 /* The remaining input chars are ignored if the callback
5573 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005574 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005575 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005576 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005577 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005578 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005579 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005580 }
5581
Walter Dörwald41980ca2007-08-16 21:55:45 +00005582 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005583 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005584
Walter Dörwald41980ca2007-08-16 21:55:45 +00005585 Py_XDECREF(errorHandler);
5586 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005587 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005588
Benjamin Peterson29060642009-01-31 22:14:21 +00005589 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005590 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005591 Py_XDECREF(errorHandler);
5592 Py_XDECREF(exc);
5593 return NULL;
5594}
5595
5596PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005597_PyUnicode_EncodeUTF32(PyObject *str,
5598 const char *errors,
5599 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005600{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005601 enum PyUnicode_Kind kind;
5602 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005603 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005604 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005605 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005606#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005607 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005608#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005609 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005610#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005611 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005612 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005613 PyObject *errorHandler = NULL;
5614 PyObject *exc = NULL;
5615 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005616
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005617 if (!PyUnicode_Check(str)) {
5618 PyErr_BadArgument();
5619 return NULL;
5620 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005621 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005622 return NULL;
5623 kind = PyUnicode_KIND(str);
5624 data = PyUnicode_DATA(str);
5625 len = PyUnicode_GET_LENGTH(str);
5626
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005627 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005628 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005629 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005630 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005631 if (v == NULL)
5632 return NULL;
5633
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005634 /* output buffer is 4-bytes aligned */
5635 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005636 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005637 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005638 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005639 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005640 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005641
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005642 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005643 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005644 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005645 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005646 else
5647 encoding = "utf-32";
5648
5649 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005650 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5651 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005652 }
5653
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005654 pos = 0;
5655 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005656 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005657
5658 if (kind == PyUnicode_2BYTE_KIND) {
5659 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5660 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005661 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005662 else {
5663 assert(kind == PyUnicode_4BYTE_KIND);
5664 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5665 &out, native_ordering);
5666 }
5667 if (pos == len)
5668 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005669
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005670 rep = unicode_encode_call_errorhandler(
5671 errors, &errorHandler,
5672 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005673 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005674 if (!rep)
5675 goto error;
5676
5677 if (PyBytes_Check(rep)) {
5678 repsize = PyBytes_GET_SIZE(rep);
5679 if (repsize & 3) {
5680 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005681 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005682 "surrogates not allowed");
5683 goto error;
5684 }
5685 moreunits = repsize / 4;
5686 }
5687 else {
5688 assert(PyUnicode_Check(rep));
5689 if (PyUnicode_READY(rep) < 0)
5690 goto error;
5691 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5692 if (!PyUnicode_IS_ASCII(rep)) {
5693 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005694 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005695 "surrogates not allowed");
5696 goto error;
5697 }
5698 }
5699
5700 /* four bytes are reserved for each surrogate */
5701 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005702 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005703 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005704 /* integer overflow */
5705 PyErr_NoMemory();
5706 goto error;
5707 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005708 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005709 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005710 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005711 }
5712
5713 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005714 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005715 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005716 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005717 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005718 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5719 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005720 }
5721
5722 Py_CLEAR(rep);
5723 }
5724
5725 /* Cut back to size actually needed. This is necessary for, for example,
5726 encoding of a string containing isolated surrogates and the 'ignore'
5727 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005728 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005729 if (nsize != PyBytes_GET_SIZE(v))
5730 _PyBytes_Resize(&v, nsize);
5731 Py_XDECREF(errorHandler);
5732 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005733 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005734 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005735 error:
5736 Py_XDECREF(rep);
5737 Py_XDECREF(errorHandler);
5738 Py_XDECREF(exc);
5739 Py_XDECREF(v);
5740 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005741}
5742
Alexander Belopolsky40018472011-02-26 01:02:56 +00005743PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005744PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5745 Py_ssize_t size,
5746 const char *errors,
5747 int byteorder)
5748{
5749 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005750 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005751 if (tmp == NULL)
5752 return NULL;
5753 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5754 Py_DECREF(tmp);
5755 return result;
5756}
5757
5758PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005759PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005760{
Victor Stinnerb960b342011-11-20 19:12:52 +01005761 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005762}
5763
Guido van Rossumd57fd912000-03-10 22:53:23 +00005764/* --- UTF-16 Codec ------------------------------------------------------- */
5765
Tim Peters772747b2001-08-09 22:21:55 +00005766PyObject *
5767PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005768 Py_ssize_t size,
5769 const char *errors,
5770 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005771{
Walter Dörwald69652032004-09-07 20:24:22 +00005772 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5773}
5774
5775PyObject *
5776PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005777 Py_ssize_t size,
5778 const char *errors,
5779 int *byteorder,
5780 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005781{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005782 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005783 Py_ssize_t startinpos;
5784 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005785 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005786 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005787 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005788 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005789 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005790 PyObject *errorHandler = NULL;
5791 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005792 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005793
Tim Peters772747b2001-08-09 22:21:55 +00005794 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005795 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005796
5797 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005798 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005799
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005800 /* Check for BOM marks (U+FEFF) in the input and adjust current
5801 byte order setting accordingly. In native mode, the leading BOM
5802 mark is skipped, in all other modes, it is copied to the output
5803 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005804 if (bo == 0 && size >= 2) {
5805 const Py_UCS4 bom = (q[1] << 8) | q[0];
5806 if (bom == 0xFEFF) {
5807 q += 2;
5808 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005809 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005810 else if (bom == 0xFFFE) {
5811 q += 2;
5812 bo = 1;
5813 }
5814 if (byteorder)
5815 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005816 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005817
Antoine Pitrou63065d72012-05-15 23:48:04 +02005818 if (q == e) {
5819 if (consumed)
5820 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005821 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005822 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005823
Christian Heimes743e0cd2012-10-17 23:52:17 +02005824#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005825 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005826 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005827#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005828 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005829 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005830#endif
Tim Peters772747b2001-08-09 22:21:55 +00005831
Antoine Pitrou63065d72012-05-15 23:48:04 +02005832 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005833 character count normally. Error handler will take care of
5834 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005835 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005836 writer.min_length = (e - q + 1) / 2;
5837 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005838 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005839
Antoine Pitrou63065d72012-05-15 23:48:04 +02005840 while (1) {
5841 Py_UCS4 ch = 0;
5842 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005843 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005844 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005845 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005846 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005847 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005848 native_ordering);
5849 else
5850 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005851 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005852 native_ordering);
5853 } else if (kind == PyUnicode_2BYTE_KIND) {
5854 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005855 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005856 native_ordering);
5857 } else {
5858 assert(kind == PyUnicode_4BYTE_KIND);
5859 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005860 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005861 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005862 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005863 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005864
Antoine Pitrou63065d72012-05-15 23:48:04 +02005865 switch (ch)
5866 {
5867 case 0:
5868 /* remaining byte at the end? (size should be even) */
5869 if (q == e || consumed)
5870 goto End;
5871 errmsg = "truncated data";
5872 startinpos = ((const char *)q) - starts;
5873 endinpos = ((const char *)e) - starts;
5874 break;
5875 /* The remaining input chars are ignored if the callback
5876 chooses to skip the input */
5877 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005878 q -= 2;
5879 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005880 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005881 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005882 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005883 endinpos = ((const char *)e) - starts;
5884 break;
5885 case 2:
5886 errmsg = "illegal encoding";
5887 startinpos = ((const char *)q) - 2 - starts;
5888 endinpos = startinpos + 2;
5889 break;
5890 case 3:
5891 errmsg = "illegal UTF-16 surrogate";
5892 startinpos = ((const char *)q) - 4 - starts;
5893 endinpos = startinpos + 2;
5894 break;
5895 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005896 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005897 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005898 continue;
5899 }
5900
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005901 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005902 errors,
5903 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005904 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005905 &starts,
5906 (const char **)&e,
5907 &startinpos,
5908 &endinpos,
5909 &exc,
5910 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005911 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005912 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 }
5914
Antoine Pitrou63065d72012-05-15 23:48:04 +02005915End:
Walter Dörwald69652032004-09-07 20:24:22 +00005916 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005917 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005918
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005919 Py_XDECREF(errorHandler);
5920 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005921 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005922
Benjamin Peterson29060642009-01-31 22:14:21 +00005923 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005924 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005925 Py_XDECREF(errorHandler);
5926 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927 return NULL;
5928}
5929
Tim Peters772747b2001-08-09 22:21:55 +00005930PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005931_PyUnicode_EncodeUTF16(PyObject *str,
5932 const char *errors,
5933 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005934{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005935 enum PyUnicode_Kind kind;
5936 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005937 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005938 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005939 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005940 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005941#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005942 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005943#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005944 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005945#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005946 const char *encoding;
5947 Py_ssize_t nsize, pos;
5948 PyObject *errorHandler = NULL;
5949 PyObject *exc = NULL;
5950 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005951
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005952 if (!PyUnicode_Check(str)) {
5953 PyErr_BadArgument();
5954 return NULL;
5955 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005956 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005957 return NULL;
5958 kind = PyUnicode_KIND(str);
5959 data = PyUnicode_DATA(str);
5960 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005961
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005962 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005963 if (kind == PyUnicode_4BYTE_KIND) {
5964 const Py_UCS4 *in = (const Py_UCS4 *)data;
5965 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005966 while (in < end) {
5967 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005968 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005969 }
5970 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005971 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005972 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005973 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005974 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005975 nsize = len + pairs + (byteorder == 0);
5976 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005977 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005979 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005981 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005982 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005983 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005984 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005985 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005986 }
5987 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005988 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005989 }
Tim Peters772747b2001-08-09 22:21:55 +00005990
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005991 if (kind == PyUnicode_1BYTE_KIND) {
5992 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5993 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005994 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005995
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005996 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005997 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005998 }
5999 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006000 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006001 }
6002 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006003 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006004 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006005
6006 pos = 0;
6007 while (pos < len) {
6008 Py_ssize_t repsize, moreunits;
6009
6010 if (kind == PyUnicode_2BYTE_KIND) {
6011 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
6012 &out, native_ordering);
6013 }
6014 else {
6015 assert(kind == PyUnicode_4BYTE_KIND);
6016 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
6017 &out, native_ordering);
6018 }
6019 if (pos == len)
6020 break;
6021
6022 rep = unicode_encode_call_errorhandler(
6023 errors, &errorHandler,
6024 encoding, "surrogates not allowed",
6025 str, &exc, pos, pos + 1, &pos);
6026 if (!rep)
6027 goto error;
6028
6029 if (PyBytes_Check(rep)) {
6030 repsize = PyBytes_GET_SIZE(rep);
6031 if (repsize & 1) {
6032 raise_encode_exception(&exc, encoding,
6033 str, pos - 1, pos,
6034 "surrogates not allowed");
6035 goto error;
6036 }
6037 moreunits = repsize / 2;
6038 }
6039 else {
6040 assert(PyUnicode_Check(rep));
6041 if (PyUnicode_READY(rep) < 0)
6042 goto error;
6043 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
6044 if (!PyUnicode_IS_ASCII(rep)) {
6045 raise_encode_exception(&exc, encoding,
6046 str, pos - 1, pos,
6047 "surrogates not allowed");
6048 goto error;
6049 }
6050 }
6051
6052 /* two bytes are reserved for each surrogate */
6053 if (moreunits > 1) {
6054 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006055 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006056 /* integer overflow */
6057 PyErr_NoMemory();
6058 goto error;
6059 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006060 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006061 goto error;
6062 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
6063 }
6064
6065 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02006066 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006067 out += moreunits;
6068 } else /* rep is unicode */ {
6069 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6070 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
6071 &out, native_ordering);
6072 }
6073
6074 Py_CLEAR(rep);
6075 }
6076
6077 /* Cut back to size actually needed. This is necessary for, for example,
6078 encoding of a string containing isolated surrogates and the 'ignore' handler
6079 is used. */
6080 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
6081 if (nsize != PyBytes_GET_SIZE(v))
6082 _PyBytes_Resize(&v, nsize);
6083 Py_XDECREF(errorHandler);
6084 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00006085 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006086 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006087 error:
6088 Py_XDECREF(rep);
6089 Py_XDECREF(errorHandler);
6090 Py_XDECREF(exc);
6091 Py_XDECREF(v);
6092 return NULL;
6093#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006094}
6095
Alexander Belopolsky40018472011-02-26 01:02:56 +00006096PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006097PyUnicode_EncodeUTF16(const Py_UNICODE *s,
6098 Py_ssize_t size,
6099 const char *errors,
6100 int byteorder)
6101{
6102 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006103 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006104 if (tmp == NULL)
6105 return NULL;
6106 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
6107 Py_DECREF(tmp);
6108 return result;
6109}
6110
6111PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006112PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006113{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006114 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115}
6116
6117/* --- Unicode Escape Codec ----------------------------------------------- */
6118
Fredrik Lundh06d12682001-01-24 07:59:11 +00006119static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00006120
Alexander Belopolsky40018472011-02-26 01:02:56 +00006121PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04006122_PyUnicode_DecodeUnicodeEscape(const char *s,
6123 Py_ssize_t size,
6124 const char *errors,
6125 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006126{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006127 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006128 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006129 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006130 PyObject *errorHandler = NULL;
6131 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006132
Eric V. Smith42454af2016-10-31 09:22:08 -04006133 // so we can remember if we've seen an invalid escape char or not
6134 *first_invalid_escape = NULL;
6135
Victor Stinner62ec3312016-09-06 17:04:34 -07006136 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006137 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006138 }
6139 /* Escaped strings will always be longer than the resulting
6140 Unicode string, so we start with size here and then reduce the
6141 length after conversion to the true value.
6142 (but if the error callback returns a long replacement string
6143 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006144 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006145 writer.min_length = size;
6146 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6147 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006148 }
6149
Guido van Rossumd57fd912000-03-10 22:53:23 +00006150 end = s + size;
6151 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006152 unsigned char c = (unsigned char) *s++;
6153 Py_UCS4 ch;
6154 int count;
6155 Py_ssize_t startinpos;
6156 Py_ssize_t endinpos;
6157 const char *message;
6158
6159#define WRITE_ASCII_CHAR(ch) \
6160 do { \
6161 assert(ch <= 127); \
6162 assert(writer.pos < writer.size); \
6163 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6164 } while(0)
6165
6166#define WRITE_CHAR(ch) \
6167 do { \
6168 if (ch <= writer.maxchar) { \
6169 assert(writer.pos < writer.size); \
6170 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6171 } \
6172 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6173 goto onError; \
6174 } \
6175 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006176
6177 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006178 if (c != '\\') {
6179 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006180 continue;
6181 }
6182
Victor Stinner62ec3312016-09-06 17:04:34 -07006183 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006184 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006185 if (s >= end) {
6186 message = "\\ at end of string";
6187 goto error;
6188 }
6189 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006190
Victor Stinner62ec3312016-09-06 17:04:34 -07006191 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006192 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193
Benjamin Peterson29060642009-01-31 22:14:21 +00006194 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006195 case '\n': continue;
6196 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6197 case '\'': WRITE_ASCII_CHAR('\''); continue;
6198 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6199 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006200 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006201 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6202 case 't': WRITE_ASCII_CHAR('\t'); continue;
6203 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6204 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006205 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006206 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006207 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006208 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209
Benjamin Peterson29060642009-01-31 22:14:21 +00006210 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211 case '0': case '1': case '2': case '3':
6212 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006213 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006214 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006215 ch = (ch<<3) + *s++ - '0';
6216 if (s < end && '0' <= *s && *s <= '7') {
6217 ch = (ch<<3) + *s++ - '0';
6218 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006220 WRITE_CHAR(ch);
6221 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222
Benjamin Peterson29060642009-01-31 22:14:21 +00006223 /* hex escapes */
6224 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006226 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006227 message = "truncated \\xXX escape";
6228 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006229
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006232 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006233 message = "truncated \\uXXXX escape";
6234 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006235
Benjamin Peterson29060642009-01-31 22:14:21 +00006236 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006237 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006238 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006239 message = "truncated \\UXXXXXXXX escape";
6240 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006241 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006242 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006243 ch <<= 4;
6244 if (c >= '0' && c <= '9') {
6245 ch += c - '0';
6246 }
6247 else if (c >= 'a' && c <= 'f') {
6248 ch += c - ('a' - 10);
6249 }
6250 else if (c >= 'A' && c <= 'F') {
6251 ch += c - ('A' - 10);
6252 }
6253 else {
6254 break;
6255 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006256 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006257 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006258 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006259 }
6260
6261 /* when we get here, ch is a 32-bit unicode character */
6262 if (ch > MAX_UNICODE) {
6263 message = "illegal Unicode character";
6264 goto error;
6265 }
6266
6267 WRITE_CHAR(ch);
6268 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006269
Benjamin Peterson29060642009-01-31 22:14:21 +00006270 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006271 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006272 if (ucnhash_CAPI == NULL) {
6273 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006274 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6275 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006276 if (ucnhash_CAPI == NULL) {
6277 PyErr_SetString(
6278 PyExc_UnicodeError,
6279 "\\N escapes not supported (can't load unicodedata module)"
6280 );
6281 goto onError;
6282 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006283 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006284
6285 message = "malformed \\N character escape";
Gregory P. Smith746b2d32018-11-13 13:16:54 -08006286 if (s < end && *s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006287 const char *start = ++s;
6288 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006289 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006290 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006291 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006292 namelen = s - start;
6293 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006294 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006295 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006296 ch = 0xffffffff; /* in case 'getcode' messes up */
6297 if (namelen <= INT_MAX &&
6298 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6299 &ch, 0)) {
6300 assert(ch <= MAX_UNICODE);
6301 WRITE_CHAR(ch);
6302 continue;
6303 }
6304 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006305 }
6306 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006307 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006308
6309 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006310 if (*first_invalid_escape == NULL) {
6311 *first_invalid_escape = s-1; /* Back up one char, since we've
6312 already incremented s. */
6313 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006314 WRITE_ASCII_CHAR('\\');
6315 WRITE_CHAR(c);
6316 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006317 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006318
6319 error:
6320 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006321 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006322 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006323 errors, &errorHandler,
6324 "unicodeescape", message,
6325 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006326 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006327 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006328 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006329 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006330
6331#undef WRITE_ASCII_CHAR
6332#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006333 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006334
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006335 Py_XDECREF(errorHandler);
6336 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006337 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006338
Benjamin Peterson29060642009-01-31 22:14:21 +00006339 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006340 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006341 Py_XDECREF(errorHandler);
6342 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343 return NULL;
6344}
6345
Eric V. Smith42454af2016-10-31 09:22:08 -04006346PyObject *
6347PyUnicode_DecodeUnicodeEscape(const char *s,
6348 Py_ssize_t size,
6349 const char *errors)
6350{
6351 const char *first_invalid_escape;
6352 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6353 &first_invalid_escape);
6354 if (result == NULL)
6355 return NULL;
6356 if (first_invalid_escape != NULL) {
6357 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6358 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006359 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006360 Py_DECREF(result);
6361 return NULL;
6362 }
6363 }
6364 return result;
6365}
6366
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006367/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006368
Alexander Belopolsky40018472011-02-26 01:02:56 +00006369PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006370PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006371{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006372 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006373 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006374 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006375 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006376 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006377 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006378
Ezio Melottie7f90372012-10-05 03:33:31 +03006379 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006380 escape.
6381
Ezio Melottie7f90372012-10-05 03:33:31 +03006382 For UCS1 strings it's '\xxx', 4 bytes per source character.
6383 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6384 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006385 */
6386
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006387 if (!PyUnicode_Check(unicode)) {
6388 PyErr_BadArgument();
6389 return NULL;
6390 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006391 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006392 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006393 }
Victor Stinner358af132015-10-12 22:36:57 +02006394
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006395 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006396 if (len == 0) {
6397 return PyBytes_FromStringAndSize(NULL, 0);
6398 }
6399
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006400 kind = PyUnicode_KIND(unicode);
6401 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006402 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6403 bytes, and 1 byte characters 4. */
6404 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006405 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 return PyErr_NoMemory();
6407 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006408 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006409 if (repr == NULL) {
6410 return NULL;
6411 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006412
Victor Stinner62ec3312016-09-06 17:04:34 -07006413 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006414 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006415 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006416
Victor Stinner62ec3312016-09-06 17:04:34 -07006417 /* U+0000-U+00ff range */
6418 if (ch < 0x100) {
6419 if (ch >= ' ' && ch < 127) {
6420 if (ch != '\\') {
6421 /* Copy printable US ASCII as-is */
6422 *p++ = (char) ch;
6423 }
6424 /* Escape backslashes */
6425 else {
6426 *p++ = '\\';
6427 *p++ = '\\';
6428 }
6429 }
Victor Stinner358af132015-10-12 22:36:57 +02006430
Victor Stinner62ec3312016-09-06 17:04:34 -07006431 /* Map special whitespace to '\t', \n', '\r' */
6432 else if (ch == '\t') {
6433 *p++ = '\\';
6434 *p++ = 't';
6435 }
6436 else if (ch == '\n') {
6437 *p++ = '\\';
6438 *p++ = 'n';
6439 }
6440 else if (ch == '\r') {
6441 *p++ = '\\';
6442 *p++ = 'r';
6443 }
6444
6445 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6446 else {
6447 *p++ = '\\';
6448 *p++ = 'x';
6449 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6450 *p++ = Py_hexdigits[ch & 0x000F];
6451 }
Tim Petersced69f82003-09-16 20:30:58 +00006452 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006453 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006454 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006455 *p++ = '\\';
6456 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006457 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6458 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6459 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6460 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006461 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006462 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6463 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006464
Victor Stinner62ec3312016-09-06 17:04:34 -07006465 /* Make sure that the first two digits are zero */
6466 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006467 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006468 *p++ = 'U';
6469 *p++ = '0';
6470 *p++ = '0';
6471 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6472 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6473 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6474 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6475 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6476 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006477 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006478 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006479
Victor Stinner62ec3312016-09-06 17:04:34 -07006480 assert(p - PyBytes_AS_STRING(repr) > 0);
6481 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6482 return NULL;
6483 }
6484 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006485}
6486
Alexander Belopolsky40018472011-02-26 01:02:56 +00006487PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006488PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6489 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006490{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006491 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006492 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006493 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006494 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006495 }
6496
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006497 result = PyUnicode_AsUnicodeEscapeString(tmp);
6498 Py_DECREF(tmp);
6499 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006500}
6501
6502/* --- Raw Unicode Escape Codec ------------------------------------------- */
6503
Alexander Belopolsky40018472011-02-26 01:02:56 +00006504PyObject *
6505PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006506 Py_ssize_t size,
6507 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006508{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006509 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006510 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006512 PyObject *errorHandler = NULL;
6513 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006514
Victor Stinner62ec3312016-09-06 17:04:34 -07006515 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006516 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006517 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006518
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519 /* Escaped strings will always be longer than the resulting
6520 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006521 length after conversion to the true value. (But decoding error
6522 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006523 _PyUnicodeWriter_Init(&writer);
Inada Naoki770847a2019-06-24 12:30:24 +09006524 writer.min_length = size;
Victor Stinner62ec3312016-09-06 17:04:34 -07006525 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6526 goto onError;
6527 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006528
Guido van Rossumd57fd912000-03-10 22:53:23 +00006529 end = s + size;
6530 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006531 unsigned char c = (unsigned char) *s++;
6532 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006533 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006534 Py_ssize_t startinpos;
6535 Py_ssize_t endinpos;
6536 const char *message;
6537
6538#define WRITE_CHAR(ch) \
6539 do { \
6540 if (ch <= writer.maxchar) { \
6541 assert(writer.pos < writer.size); \
6542 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6543 } \
6544 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6545 goto onError; \
6546 } \
6547 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548
Benjamin Peterson29060642009-01-31 22:14:21 +00006549 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006550 if (c != '\\' || s >= end) {
6551 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006552 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006553 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006554
Victor Stinner62ec3312016-09-06 17:04:34 -07006555 c = (unsigned char) *s++;
6556 if (c == 'u') {
6557 count = 4;
6558 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006559 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006560 else if (c == 'U') {
6561 count = 8;
6562 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006563 }
6564 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006565 assert(writer.pos < writer.size);
6566 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6567 WRITE_CHAR(c);
6568 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006569 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006570 startinpos = s - starts - 2;
6571
6572 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6573 for (ch = 0; count && s < end; ++s, --count) {
6574 c = (unsigned char)*s;
6575 ch <<= 4;
6576 if (c >= '0' && c <= '9') {
6577 ch += c - '0';
6578 }
6579 else if (c >= 'a' && c <= 'f') {
6580 ch += c - ('a' - 10);
6581 }
6582 else if (c >= 'A' && c <= 'F') {
6583 ch += c - ('A' - 10);
6584 }
6585 else {
6586 break;
6587 }
6588 }
6589 if (!count) {
6590 if (ch <= MAX_UNICODE) {
6591 WRITE_CHAR(ch);
6592 continue;
6593 }
6594 message = "\\Uxxxxxxxx out of range";
6595 }
6596
6597 endinpos = s-starts;
6598 writer.min_length = end - s + writer.pos;
6599 if (unicode_decode_call_errorhandler_writer(
6600 errors, &errorHandler,
6601 "rawunicodeescape", message,
6602 &starts, &end, &startinpos, &endinpos, &exc, &s,
6603 &writer)) {
6604 goto onError;
6605 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006606 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006607
6608#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006609 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006610 Py_XDECREF(errorHandler);
6611 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006612 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006613
Benjamin Peterson29060642009-01-31 22:14:21 +00006614 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006615 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006616 Py_XDECREF(errorHandler);
6617 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006618 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006619
Guido van Rossumd57fd912000-03-10 22:53:23 +00006620}
6621
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006622
Alexander Belopolsky40018472011-02-26 01:02:56 +00006623PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006624PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006625{
Victor Stinner62ec3312016-09-06 17:04:34 -07006626 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006627 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006628 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006629 int kind;
6630 void *data;
6631 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006632
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006633 if (!PyUnicode_Check(unicode)) {
6634 PyErr_BadArgument();
6635 return NULL;
6636 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006637 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006638 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006639 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006640 kind = PyUnicode_KIND(unicode);
6641 data = PyUnicode_DATA(unicode);
6642 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006643 if (kind == PyUnicode_1BYTE_KIND) {
6644 return PyBytes_FromStringAndSize(data, len);
6645 }
Victor Stinner0e368262011-11-10 20:12:49 +01006646
Victor Stinner62ec3312016-09-06 17:04:34 -07006647 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6648 bytes, and 1 byte characters 4. */
6649 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006650
Victor Stinner62ec3312016-09-06 17:04:34 -07006651 if (len > PY_SSIZE_T_MAX / expandsize) {
6652 return PyErr_NoMemory();
6653 }
6654 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6655 if (repr == NULL) {
6656 return NULL;
6657 }
6658 if (len == 0) {
6659 return repr;
6660 }
6661
6662 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006663 for (pos = 0; pos < len; pos++) {
6664 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006665
Victor Stinner62ec3312016-09-06 17:04:34 -07006666 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6667 if (ch < 0x100) {
6668 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006669 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006670 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006671 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006672 *p++ = '\\';
6673 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006674 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6675 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6676 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6677 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006678 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006679 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6680 else {
6681 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6682 *p++ = '\\';
6683 *p++ = 'U';
6684 *p++ = '0';
6685 *p++ = '0';
6686 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6687 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6688 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6689 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6690 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6691 *p++ = Py_hexdigits[ch & 15];
6692 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006693 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006694
Victor Stinner62ec3312016-09-06 17:04:34 -07006695 assert(p > PyBytes_AS_STRING(repr));
6696 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6697 return NULL;
6698 }
6699 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006700}
6701
Alexander Belopolsky40018472011-02-26 01:02:56 +00006702PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006703PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6704 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006705{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006706 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006707 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006708 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006709 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006710 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6711 Py_DECREF(tmp);
6712 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006713}
6714
6715/* --- Latin-1 Codec ------------------------------------------------------ */
6716
Alexander Belopolsky40018472011-02-26 01:02:56 +00006717PyObject *
6718PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006719 Py_ssize_t size,
6720 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006721{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006722 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006723 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006724}
6725
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006726/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006727static void
6728make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006729 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006730 PyObject *unicode,
6731 Py_ssize_t startpos, Py_ssize_t endpos,
6732 const char *reason)
6733{
6734 if (*exceptionObject == NULL) {
6735 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006736 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006737 encoding, unicode, startpos, endpos, reason);
6738 }
6739 else {
6740 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6741 goto onError;
6742 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6743 goto onError;
6744 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6745 goto onError;
6746 return;
6747 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006748 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006749 }
6750}
6751
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006752/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006753static void
6754raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006755 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006756 PyObject *unicode,
6757 Py_ssize_t startpos, Py_ssize_t endpos,
6758 const char *reason)
6759{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006760 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006761 encoding, unicode, startpos, endpos, reason);
6762 if (*exceptionObject != NULL)
6763 PyCodec_StrictErrors(*exceptionObject);
6764}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006765
6766/* error handling callback helper:
6767 build arguments, call the callback and check the arguments,
6768 put the result into newpos and return the replacement string, which
6769 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006770static PyObject *
6771unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006772 PyObject **errorHandler,
6773 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006774 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006775 Py_ssize_t startpos, Py_ssize_t endpos,
6776 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006777{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006778 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006779 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006780 PyObject *restuple;
6781 PyObject *resunicode;
6782
6783 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006784 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006785 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006786 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006787 }
6788
Benjamin Petersonbac79492012-01-14 13:34:47 -05006789 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006790 return NULL;
6791 len = PyUnicode_GET_LENGTH(unicode);
6792
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006793 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006794 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006795 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006797
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006798 restuple = PyObject_CallFunctionObjArgs(
6799 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006800 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006801 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006802 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006803 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006804 Py_DECREF(restuple);
6805 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006806 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006807 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006808 &resunicode, newpos)) {
6809 Py_DECREF(restuple);
6810 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006811 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006812 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6813 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6814 Py_DECREF(restuple);
6815 return NULL;
6816 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006817 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006818 *newpos = len + *newpos;
6819 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006820 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006821 Py_DECREF(restuple);
6822 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006823 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006824 Py_INCREF(resunicode);
6825 Py_DECREF(restuple);
6826 return resunicode;
6827}
6828
Alexander Belopolsky40018472011-02-26 01:02:56 +00006829static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006830unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006831 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006832 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006833{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006834 /* input state */
6835 Py_ssize_t pos=0, size;
6836 int kind;
6837 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006838 /* pointer into the output */
6839 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006840 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6841 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006842 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006843 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006844 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006845 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006846 /* output object */
6847 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006848
Benjamin Petersonbac79492012-01-14 13:34:47 -05006849 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006850 return NULL;
6851 size = PyUnicode_GET_LENGTH(unicode);
6852 kind = PyUnicode_KIND(unicode);
6853 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006854 /* allocate enough for a simple encoding without
6855 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006856 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006857 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006858
6859 _PyBytesWriter_Init(&writer);
6860 str = _PyBytesWriter_Alloc(&writer, size);
6861 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006862 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006863
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006864 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006865 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006866
Benjamin Peterson29060642009-01-31 22:14:21 +00006867 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006868 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006869 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006870 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006871 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006872 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006873 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006874 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006876 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006877 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006878 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006879
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006880 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006881 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006882
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006883 /* Only overallocate the buffer if it's not the last write */
6884 writer.overallocate = (collend < size);
6885
Benjamin Peterson29060642009-01-31 22:14:21 +00006886 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006887 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006888 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02006889
6890 switch (error_handler) {
6891 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006892 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006893 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006894
6895 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006896 memset(str, '?', collend - collstart);
6897 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006898 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006899 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006900 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006901 break;
Victor Stinner50149202015-09-22 00:26:54 +02006902
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006903 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006904 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006905 writer.min_size -= (collend - collstart);
6906 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006907 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006908 if (str == NULL)
6909 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006910 pos = collend;
6911 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006912
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006913 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006914 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006915 writer.min_size -= (collend - collstart);
6916 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006917 unicode, collstart, collend);
6918 if (str == NULL)
6919 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006920 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006921 break;
Victor Stinner50149202015-09-22 00:26:54 +02006922
Victor Stinnerc3713e92015-09-29 12:32:13 +02006923 case _Py_ERROR_SURROGATEESCAPE:
6924 for (i = collstart; i < collend; ++i) {
6925 ch = PyUnicode_READ(kind, data, i);
6926 if (ch < 0xdc80 || 0xdcff < ch) {
6927 /* Not a UTF-8b surrogate */
6928 break;
6929 }
6930 *str++ = (char)(ch - 0xdc00);
6931 ++pos;
6932 }
6933 if (i >= collend)
6934 break;
6935 collstart = pos;
6936 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006937 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006938
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006940 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6941 encoding, reason, unicode, &exc,
6942 collstart, collend, &newpos);
6943 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006944 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006945
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006946 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006947 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006948
Victor Stinner6bd525b2015-10-09 13:10:05 +02006949 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006950 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006951 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006952 PyBytes_AS_STRING(rep),
6953 PyBytes_GET_SIZE(rep));
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006954 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006955 else {
6956 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006957
Victor Stinner6bd525b2015-10-09 13:10:05 +02006958 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006959 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006960
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006961 if (limit == 256 ?
6962 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6963 !PyUnicode_IS_ASCII(rep))
6964 {
6965 /* Not all characters are smaller than limit */
6966 raise_encode_exception(&exc, encoding, unicode,
6967 collstart, collend, reason);
6968 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006969 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006970 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6971 str = _PyBytesWriter_WriteBytes(&writer, str,
6972 PyUnicode_DATA(rep),
6973 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 }
Alexey Izbyshev74a307d2018-08-19 21:52:04 +03006975 if (str == NULL)
6976 goto onError;
6977
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006978 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006979 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006980 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006981
6982 /* If overallocation was disabled, ensure that it was the last
6983 write. Otherwise, we missed an optimization */
6984 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006985 }
6986 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006987
Victor Stinner50149202015-09-22 00:26:54 +02006988 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006989 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006990 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006991
6992 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006993 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006994 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006995 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006996 Py_XDECREF(exc);
6997 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006998}
6999
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007000/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007001PyObject *
7002PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03007003 Py_ssize_t size,
7004 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007005{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007006 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007007 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007008 if (unicode == NULL)
7009 return NULL;
7010 result = unicode_encode_ucs1(unicode, errors, 256);
7011 Py_DECREF(unicode);
7012 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007013}
7014
Alexander Belopolsky40018472011-02-26 01:02:56 +00007015PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007016_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007017{
7018 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007019 PyErr_BadArgument();
7020 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007021 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007022 if (PyUnicode_READY(unicode) == -1)
7023 return NULL;
7024 /* Fast path: if it is a one-byte string, construct
7025 bytes object directly. */
7026 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7027 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7028 PyUnicode_GET_LENGTH(unicode));
7029 /* Non-Latin-1 characters present. Defer to above function to
7030 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007031 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007032}
7033
7034PyObject*
7035PyUnicode_AsLatin1String(PyObject *unicode)
7036{
7037 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007038}
7039
7040/* --- 7-bit ASCII Codec -------------------------------------------------- */
7041
Alexander Belopolsky40018472011-02-26 01:02:56 +00007042PyObject *
7043PyUnicode_DecodeASCII(const char *s,
7044 Py_ssize_t size,
7045 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007046{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007047 const char *starts = s;
Inada Naoki770847a2019-06-24 12:30:24 +09007048 const char *e = s + size;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007049 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007050 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007051 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00007052
Guido van Rossumd57fd912000-03-10 22:53:23 +00007053 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02007054 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007055
Guido van Rossumd57fd912000-03-10 22:53:23 +00007056 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02007057 if (size == 1 && (unsigned char)s[0] < 128)
7058 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007059
Inada Naoki770847a2019-06-24 12:30:24 +09007060 // Shortcut for simple case
7061 PyObject *u = PyUnicode_New(size, 127);
7062 if (u == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02007063 return NULL;
Inada Naoki770847a2019-06-24 12:30:24 +09007064 }
7065 Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_DATA(u));
7066 if (outpos == size) {
7067 return u;
7068 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007069
Inada Naoki770847a2019-06-24 12:30:24 +09007070 _PyUnicodeWriter writer;
7071 _PyUnicodeWriter_InitWithBuffer(&writer, u);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007072 writer.pos = outpos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007073
Inada Naoki770847a2019-06-24 12:30:24 +09007074 s += outpos;
7075 int kind = writer.kind;
7076 void *data = writer.data;
7077 Py_ssize_t startinpos, endinpos;
7078
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007079 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007080 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007081 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007082 PyUnicode_WRITE(kind, data, writer.pos, c);
7083 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007084 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007085 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007086 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007087
7088 /* byte outsize range 0x00..0x7f: call the error handler */
7089
7090 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02007091 error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007092
7093 switch (error_handler)
7094 {
7095 case _Py_ERROR_REPLACE:
7096 case _Py_ERROR_SURROGATEESCAPE:
7097 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007098 but we may switch to UCS2 at the first write */
7099 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7100 goto onError;
7101 kind = writer.kind;
7102 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007103
7104 if (error_handler == _Py_ERROR_REPLACE)
7105 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7106 else
7107 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7108 writer.pos++;
7109 ++s;
7110 break;
7111
7112 case _Py_ERROR_IGNORE:
7113 ++s;
7114 break;
7115
7116 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007117 startinpos = s-starts;
7118 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007119 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007120 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007121 "ascii", "ordinal not in range(128)",
7122 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007123 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007124 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007125 kind = writer.kind;
7126 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007127 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007128 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007129 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007130 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007131 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007132
Benjamin Peterson29060642009-01-31 22:14:21 +00007133 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007134 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007135 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007136 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007137 return NULL;
7138}
7139
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007140/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007141PyObject *
7142PyUnicode_EncodeASCII(const Py_UNICODE *p,
7143 Py_ssize_t size,
7144 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007145{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007146 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007147 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007148 if (unicode == NULL)
7149 return NULL;
7150 result = unicode_encode_ucs1(unicode, errors, 128);
7151 Py_DECREF(unicode);
7152 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007153}
7154
Alexander Belopolsky40018472011-02-26 01:02:56 +00007155PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007156_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007157{
7158 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007159 PyErr_BadArgument();
7160 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007161 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007162 if (PyUnicode_READY(unicode) == -1)
7163 return NULL;
7164 /* Fast path: if it is an ASCII-only string, construct bytes object
7165 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007166 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007167 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7168 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007169 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007170}
7171
7172PyObject *
7173PyUnicode_AsASCIIString(PyObject *unicode)
7174{
7175 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007176}
7177
Steve Dowercc16be82016-09-08 10:35:16 -07007178#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007179
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007180/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007181
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007182#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007183#define NEED_RETRY
7184#endif
7185
Victor Stinner3a50e702011-10-18 21:21:00 +02007186#ifndef WC_ERR_INVALID_CHARS
7187# define WC_ERR_INVALID_CHARS 0x0080
7188#endif
7189
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007190static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007191code_page_name(UINT code_page, PyObject **obj)
7192{
7193 *obj = NULL;
7194 if (code_page == CP_ACP)
7195 return "mbcs";
7196 if (code_page == CP_UTF7)
7197 return "CP_UTF7";
7198 if (code_page == CP_UTF8)
7199 return "CP_UTF8";
7200
7201 *obj = PyBytes_FromFormat("cp%u", code_page);
7202 if (*obj == NULL)
7203 return NULL;
7204 return PyBytes_AS_STRING(*obj);
7205}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007206
Victor Stinner3a50e702011-10-18 21:21:00 +02007207static DWORD
7208decode_code_page_flags(UINT code_page)
7209{
7210 if (code_page == CP_UTF7) {
7211 /* The CP_UTF7 decoder only supports flags=0 */
7212 return 0;
7213 }
7214 else
7215 return MB_ERR_INVALID_CHARS;
7216}
7217
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007218/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 * Decode a byte string from a Windows code page into unicode object in strict
7220 * mode.
7221 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007222 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7223 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007224 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007225static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007226decode_code_page_strict(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007227 wchar_t **buf,
7228 Py_ssize_t *bufsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007229 const char *in,
7230 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007231{
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007232 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner24729f32011-11-10 20:31:37 +01007233 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007235
7236 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 assert(insize > 0);
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007238 while ((outsize = MultiByteToWideChar(code_page, flags,
7239 in, insize, NULL, 0)) <= 0)
7240 {
7241 if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
7242 goto error;
7243 }
7244 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7245 flags = 0;
7246 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007247
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007248 /* Extend a wchar_t* buffer */
7249 Py_ssize_t n = *bufsize; /* Get the current length */
7250 if (widechar_resize(buf, bufsize, n + outsize) < 0) {
7251 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007252 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007253 out = *buf + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007254
7255 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007256 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7257 if (outsize <= 0)
7258 goto error;
7259 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007260
Victor Stinner3a50e702011-10-18 21:21:00 +02007261error:
7262 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7263 return -2;
7264 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007265 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007266}
7267
Victor Stinner3a50e702011-10-18 21:21:00 +02007268/*
7269 * Decode a byte string from a code page into unicode object with an error
7270 * handler.
7271 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007272 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 * UnicodeDecodeError exception and returns -1 on error.
7274 */
7275static int
7276decode_code_page_errors(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007277 wchar_t **buf,
7278 Py_ssize_t *bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007279 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007280 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007281{
7282 const char *startin = in;
7283 const char *endin = in + size;
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007284 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007285 /* Ideally, we should get reason from FormatMessage. This is the Windows
7286 2000 English version of the message. */
7287 const char *reason = "No mapping for the Unicode character exists "
7288 "in the target code page.";
7289 /* each step cannot decode more than 1 character, but a character can be
7290 represented as a surrogate pair */
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007291 wchar_t buffer[2], *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007292 int insize;
7293 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007294 PyObject *errorHandler = NULL;
7295 PyObject *exc = NULL;
7296 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007297 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007298 DWORD err;
7299 int ret = -1;
7300
7301 assert(size > 0);
7302
7303 encoding = code_page_name(code_page, &encoding_obj);
7304 if (encoding == NULL)
7305 return -1;
7306
Victor Stinner7d00cc12014-03-17 23:08:06 +01007307 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007308 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7309 UnicodeDecodeError. */
7310 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7311 if (exc != NULL) {
7312 PyCodec_StrictErrors(exc);
7313 Py_CLEAR(exc);
7314 }
7315 goto error;
7316 }
7317
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007318 /* Extend a wchar_t* buffer */
7319 Py_ssize_t n = *bufsize; /* Get the current length */
7320 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7321 PyErr_NoMemory();
7322 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007323 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007324 if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
7325 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007326 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007327 out = *buf + n;
Victor Stinner3a50e702011-10-18 21:21:00 +02007328
7329 /* Decode the byte string character per character */
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 while (in < endin)
7331 {
7332 /* Decode a character */
7333 insize = 1;
7334 do
7335 {
7336 outsize = MultiByteToWideChar(code_page, flags,
7337 in, insize,
7338 buffer, Py_ARRAY_LENGTH(buffer));
7339 if (outsize > 0)
7340 break;
7341 err = GetLastError();
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007342 if (err == ERROR_INVALID_FLAGS && flags) {
7343 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7344 flags = 0;
7345 continue;
7346 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007347 if (err != ERROR_NO_UNICODE_TRANSLATION
7348 && err != ERROR_INSUFFICIENT_BUFFER)
7349 {
7350 PyErr_SetFromWindowsErr(0);
7351 goto error;
7352 }
7353 insize++;
7354 }
7355 /* 4=maximum length of a UTF-8 sequence */
7356 while (insize <= 4 && (in + insize) <= endin);
7357
7358 if (outsize <= 0) {
7359 Py_ssize_t startinpos, endinpos, outpos;
7360
Victor Stinner7d00cc12014-03-17 23:08:06 +01007361 /* last character in partial decode? */
7362 if (in + insize >= endin && !final)
7363 break;
7364
Victor Stinner3a50e702011-10-18 21:21:00 +02007365 startinpos = in - startin;
7366 endinpos = startinpos + 1;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007367 outpos = out - *buf;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007368 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007369 errors, &errorHandler,
7370 encoding, reason,
7371 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007372 buf, bufsize, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007373 {
7374 goto error;
7375 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007376 out = *buf + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007377 }
7378 else {
7379 in += insize;
7380 memcpy(out, buffer, outsize * sizeof(wchar_t));
7381 out += outsize;
7382 }
7383 }
7384
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007385 /* Shrink the buffer */
7386 assert(out - *buf <= *bufsize);
7387 *bufsize = out - *buf;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007388 /* (in - startin) <= size and size is an int */
7389 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007390
7391error:
7392 Py_XDECREF(encoding_obj);
7393 Py_XDECREF(errorHandler);
7394 Py_XDECREF(exc);
7395 return ret;
7396}
7397
Victor Stinner3a50e702011-10-18 21:21:00 +02007398static PyObject *
7399decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007400 const char *s, Py_ssize_t size,
7401 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007402{
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007403 wchar_t *buf = NULL;
7404 Py_ssize_t bufsize = 0;
Victor Stinner76a31a62011-11-04 00:05:13 +01007405 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007406
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 if (code_page < 0) {
7408 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7409 return NULL;
7410 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007411 if (size < 0) {
7412 PyErr_BadInternalCall();
7413 return NULL;
7414 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007415
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007416 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007417 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007418
Victor Stinner76a31a62011-11-04 00:05:13 +01007419 do
7420 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007421#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007422 if (size > INT_MAX) {
7423 chunk_size = INT_MAX;
7424 final = 0;
7425 done = 0;
7426 }
7427 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007428#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007429 {
7430 chunk_size = (int)size;
7431 final = (consumed == NULL);
7432 done = 1;
7433 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007434
Victor Stinner76a31a62011-11-04 00:05:13 +01007435 if (chunk_size == 0 && done) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007436 if (buf != NULL)
Victor Stinner76a31a62011-11-04 00:05:13 +01007437 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007438 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007439 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007440
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007441 converted = decode_code_page_strict(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007442 s, chunk_size);
7443 if (converted == -2)
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007444 converted = decode_code_page_errors(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007445 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007446 errors, final);
7447 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007448
7449 if (converted < 0) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007450 PyMem_Free(buf);
Victor Stinner76a31a62011-11-04 00:05:13 +01007451 return NULL;
7452 }
7453
7454 if (consumed)
7455 *consumed += converted;
7456
7457 s += converted;
7458 size -= converted;
7459 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007460
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007461 PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
7462 PyMem_Free(buf);
7463 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007464}
7465
Alexander Belopolsky40018472011-02-26 01:02:56 +00007466PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007467PyUnicode_DecodeCodePageStateful(int code_page,
7468 const char *s,
7469 Py_ssize_t size,
7470 const char *errors,
7471 Py_ssize_t *consumed)
7472{
7473 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7474}
7475
7476PyObject *
7477PyUnicode_DecodeMBCSStateful(const char *s,
7478 Py_ssize_t size,
7479 const char *errors,
7480 Py_ssize_t *consumed)
7481{
7482 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7483}
7484
7485PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007486PyUnicode_DecodeMBCS(const char *s,
7487 Py_ssize_t size,
7488 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007489{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007490 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7491}
7492
Victor Stinner3a50e702011-10-18 21:21:00 +02007493static DWORD
7494encode_code_page_flags(UINT code_page, const char *errors)
7495{
7496 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007497 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007498 }
7499 else if (code_page == CP_UTF7) {
7500 /* CP_UTF7 only supports flags=0 */
7501 return 0;
7502 }
7503 else {
7504 if (errors != NULL && strcmp(errors, "replace") == 0)
7505 return 0;
7506 else
7507 return WC_NO_BEST_FIT_CHARS;
7508 }
7509}
7510
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007511/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007512 * Encode a Unicode string to a Windows code page into a byte string in strict
7513 * mode.
7514 *
7515 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007516 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007517 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007518static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007519encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007520 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007521 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007522{
Victor Stinner554f3f02010-06-16 23:33:54 +00007523 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007524 BOOL *pusedDefaultChar = &usedDefaultChar;
7525 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007526 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007527 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007528 const DWORD flags = encode_code_page_flags(code_page, NULL);
7529 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007530 /* Create a substring so that we can get the UTF-16 representation
7531 of just the slice under consideration. */
7532 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007533
Martin v. Löwis3d325192011-11-04 18:23:06 +01007534 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007535
Victor Stinner3a50e702011-10-18 21:21:00 +02007536 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007537 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007538 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007539 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007540
Victor Stinner2fc507f2011-11-04 20:06:39 +01007541 substring = PyUnicode_Substring(unicode, offset, offset+len);
7542 if (substring == NULL)
7543 return -1;
7544 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7545 if (p == NULL) {
7546 Py_DECREF(substring);
7547 return -1;
7548 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007549 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007550
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007551 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007552 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007553 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007554 NULL, 0,
7555 NULL, pusedDefaultChar);
7556 if (outsize <= 0)
7557 goto error;
7558 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007559 if (pusedDefaultChar && *pusedDefaultChar) {
7560 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007562 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007563
Victor Stinner3a50e702011-10-18 21:21:00 +02007564 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007565 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007566 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007567 if (*outbytes == NULL) {
7568 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007569 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007570 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007571 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007572 }
7573 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007574 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 const Py_ssize_t n = PyBytes_Size(*outbytes);
7576 if (outsize > PY_SSIZE_T_MAX - n) {
7577 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007578 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007579 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007580 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007581 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7582 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007583 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007584 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007585 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007586 }
7587
7588 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007589 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007590 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007591 out, outsize,
7592 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007593 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007594 if (outsize <= 0)
7595 goto error;
7596 if (pusedDefaultChar && *pusedDefaultChar)
7597 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007598 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007599
Victor Stinner3a50e702011-10-18 21:21:00 +02007600error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007601 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007602 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7603 return -2;
7604 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007605 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007606}
7607
Victor Stinner3a50e702011-10-18 21:21:00 +02007608/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007609 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007610 * error handler.
7611 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007612 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007613 * -1 on other error.
7614 */
7615static int
7616encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007617 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007618 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007619{
Victor Stinner3a50e702011-10-18 21:21:00 +02007620 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007621 Py_ssize_t pos = unicode_offset;
7622 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007623 /* Ideally, we should get reason from FormatMessage. This is the Windows
7624 2000 English version of the message. */
7625 const char *reason = "invalid character";
7626 /* 4=maximum length of a UTF-8 sequence */
7627 char buffer[4];
7628 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7629 Py_ssize_t outsize;
7630 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007631 PyObject *errorHandler = NULL;
7632 PyObject *exc = NULL;
7633 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007634 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007635 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007636 PyObject *rep;
7637 int ret = -1;
7638
7639 assert(insize > 0);
7640
7641 encoding = code_page_name(code_page, &encoding_obj);
7642 if (encoding == NULL)
7643 return -1;
7644
7645 if (errors == NULL || strcmp(errors, "strict") == 0) {
7646 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7647 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007648 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007649 if (exc != NULL) {
7650 PyCodec_StrictErrors(exc);
7651 Py_DECREF(exc);
7652 }
7653 Py_XDECREF(encoding_obj);
7654 return -1;
7655 }
7656
7657 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7658 pusedDefaultChar = &usedDefaultChar;
7659 else
7660 pusedDefaultChar = NULL;
7661
7662 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7663 PyErr_NoMemory();
7664 goto error;
7665 }
7666 outsize = insize * Py_ARRAY_LENGTH(buffer);
7667
7668 if (*outbytes == NULL) {
7669 /* Create string object */
7670 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7671 if (*outbytes == NULL)
7672 goto error;
7673 out = PyBytes_AS_STRING(*outbytes);
7674 }
7675 else {
7676 /* Extend string object */
7677 Py_ssize_t n = PyBytes_Size(*outbytes);
7678 if (n > PY_SSIZE_T_MAX - outsize) {
7679 PyErr_NoMemory();
7680 goto error;
7681 }
7682 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7683 goto error;
7684 out = PyBytes_AS_STRING(*outbytes) + n;
7685 }
7686
7687 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007688 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007689 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007690 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7691 wchar_t chars[2];
7692 int charsize;
7693 if (ch < 0x10000) {
7694 chars[0] = (wchar_t)ch;
7695 charsize = 1;
7696 }
7697 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007698 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7699 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007700 charsize = 2;
7701 }
7702
Victor Stinner3a50e702011-10-18 21:21:00 +02007703 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007704 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007705 buffer, Py_ARRAY_LENGTH(buffer),
7706 NULL, pusedDefaultChar);
7707 if (outsize > 0) {
7708 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7709 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007710 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007711 memcpy(out, buffer, outsize);
7712 out += outsize;
7713 continue;
7714 }
7715 }
7716 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7717 PyErr_SetFromWindowsErr(0);
7718 goto error;
7719 }
7720
Victor Stinner3a50e702011-10-18 21:21:00 +02007721 rep = unicode_encode_call_errorhandler(
7722 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007723 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007724 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007725 if (rep == NULL)
7726 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007727 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007728
7729 if (PyBytes_Check(rep)) {
7730 outsize = PyBytes_GET_SIZE(rep);
7731 if (outsize != 1) {
7732 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7733 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7734 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7735 Py_DECREF(rep);
7736 goto error;
7737 }
7738 out = PyBytes_AS_STRING(*outbytes) + offset;
7739 }
7740 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7741 out += outsize;
7742 }
7743 else {
7744 Py_ssize_t i;
7745 enum PyUnicode_Kind kind;
7746 void *data;
7747
Benjamin Petersonbac79492012-01-14 13:34:47 -05007748 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007749 Py_DECREF(rep);
7750 goto error;
7751 }
7752
7753 outsize = PyUnicode_GET_LENGTH(rep);
7754 if (outsize != 1) {
7755 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7756 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7757 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7758 Py_DECREF(rep);
7759 goto error;
7760 }
7761 out = PyBytes_AS_STRING(*outbytes) + offset;
7762 }
7763 kind = PyUnicode_KIND(rep);
7764 data = PyUnicode_DATA(rep);
7765 for (i=0; i < outsize; i++) {
7766 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7767 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007768 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007769 encoding, unicode,
7770 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007771 "unable to encode error handler result to ASCII");
7772 Py_DECREF(rep);
7773 goto error;
7774 }
7775 *out = (unsigned char)ch;
7776 out++;
7777 }
7778 }
7779 Py_DECREF(rep);
7780 }
7781 /* write a NUL byte */
7782 *out = 0;
7783 outsize = out - PyBytes_AS_STRING(*outbytes);
7784 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7785 if (_PyBytes_Resize(outbytes, outsize) < 0)
7786 goto error;
7787 ret = 0;
7788
7789error:
7790 Py_XDECREF(encoding_obj);
7791 Py_XDECREF(errorHandler);
7792 Py_XDECREF(exc);
7793 return ret;
7794}
7795
Victor Stinner3a50e702011-10-18 21:21:00 +02007796static PyObject *
7797encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007798 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007799 const char *errors)
7800{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007801 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007802 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007803 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007804 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007805
Victor Stinner29dacf22015-01-26 16:41:32 +01007806 if (!PyUnicode_Check(unicode)) {
7807 PyErr_BadArgument();
7808 return NULL;
7809 }
7810
Benjamin Petersonbac79492012-01-14 13:34:47 -05007811 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007812 return NULL;
7813 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007814
Victor Stinner3a50e702011-10-18 21:21:00 +02007815 if (code_page < 0) {
7816 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7817 return NULL;
7818 }
7819
Martin v. Löwis3d325192011-11-04 18:23:06 +01007820 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007821 return PyBytes_FromStringAndSize(NULL, 0);
7822
Victor Stinner7581cef2011-11-03 22:32:33 +01007823 offset = 0;
7824 do
7825 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007826#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007827 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007828 chunks. */
7829 if (len > INT_MAX/2) {
7830 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007831 done = 0;
7832 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007833 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007834#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007835 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007836 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007837 done = 1;
7838 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007839
Victor Stinner76a31a62011-11-04 00:05:13 +01007840 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007841 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007842 errors);
7843 if (ret == -2)
7844 ret = encode_code_page_errors(code_page, &outbytes,
7845 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007846 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007847 if (ret < 0) {
7848 Py_XDECREF(outbytes);
7849 return NULL;
7850 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007851
Victor Stinner7581cef2011-11-03 22:32:33 +01007852 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007853 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007854 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007855
Victor Stinner3a50e702011-10-18 21:21:00 +02007856 return outbytes;
7857}
7858
7859PyObject *
7860PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7861 Py_ssize_t size,
7862 const char *errors)
7863{
Victor Stinner7581cef2011-11-03 22:32:33 +01007864 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007865 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007866 if (unicode == NULL)
7867 return NULL;
7868 res = encode_code_page(CP_ACP, unicode, errors);
7869 Py_DECREF(unicode);
7870 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007871}
7872
7873PyObject *
7874PyUnicode_EncodeCodePage(int code_page,
7875 PyObject *unicode,
7876 const char *errors)
7877{
Victor Stinner7581cef2011-11-03 22:32:33 +01007878 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007879}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007880
Alexander Belopolsky40018472011-02-26 01:02:56 +00007881PyObject *
7882PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007883{
Victor Stinner7581cef2011-11-03 22:32:33 +01007884 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007885}
7886
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007887#undef NEED_RETRY
7888
Steve Dowercc16be82016-09-08 10:35:16 -07007889#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007890
Guido van Rossumd57fd912000-03-10 22:53:23 +00007891/* --- Character Mapping Codec -------------------------------------------- */
7892
Victor Stinnerfb161b12013-04-18 01:44:27 +02007893static int
7894charmap_decode_string(const char *s,
7895 Py_ssize_t size,
7896 PyObject *mapping,
7897 const char *errors,
7898 _PyUnicodeWriter *writer)
7899{
7900 const char *starts = s;
7901 const char *e;
7902 Py_ssize_t startinpos, endinpos;
7903 PyObject *errorHandler = NULL, *exc = NULL;
7904 Py_ssize_t maplen;
7905 enum PyUnicode_Kind mapkind;
7906 void *mapdata;
7907 Py_UCS4 x;
7908 unsigned char ch;
7909
7910 if (PyUnicode_READY(mapping) == -1)
7911 return -1;
7912
7913 maplen = PyUnicode_GET_LENGTH(mapping);
7914 mapdata = PyUnicode_DATA(mapping);
7915 mapkind = PyUnicode_KIND(mapping);
7916
7917 e = s + size;
7918
7919 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7920 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7921 * is disabled in encoding aliases, latin1 is preferred because
7922 * its implementation is faster. */
7923 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7924 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7925 Py_UCS4 maxchar = writer->maxchar;
7926
7927 assert (writer->kind == PyUnicode_1BYTE_KIND);
7928 while (s < e) {
7929 ch = *s;
7930 x = mapdata_ucs1[ch];
7931 if (x > maxchar) {
7932 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7933 goto onError;
7934 maxchar = writer->maxchar;
7935 outdata = (Py_UCS1 *)writer->data;
7936 }
7937 outdata[writer->pos] = x;
7938 writer->pos++;
7939 ++s;
7940 }
7941 return 0;
7942 }
7943
7944 while (s < e) {
7945 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7946 enum PyUnicode_Kind outkind = writer->kind;
7947 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7948 if (outkind == PyUnicode_1BYTE_KIND) {
7949 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7950 Py_UCS4 maxchar = writer->maxchar;
7951 while (s < e) {
7952 ch = *s;
7953 x = mapdata_ucs2[ch];
7954 if (x > maxchar)
7955 goto Error;
7956 outdata[writer->pos] = x;
7957 writer->pos++;
7958 ++s;
7959 }
7960 break;
7961 }
7962 else if (outkind == PyUnicode_2BYTE_KIND) {
7963 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7964 while (s < e) {
7965 ch = *s;
7966 x = mapdata_ucs2[ch];
7967 if (x == 0xFFFE)
7968 goto Error;
7969 outdata[writer->pos] = x;
7970 writer->pos++;
7971 ++s;
7972 }
7973 break;
7974 }
7975 }
7976 ch = *s;
7977
7978 if (ch < maplen)
7979 x = PyUnicode_READ(mapkind, mapdata, ch);
7980 else
7981 x = 0xfffe; /* invalid value */
7982Error:
7983 if (x == 0xfffe)
7984 {
7985 /* undefined mapping */
7986 startinpos = s-starts;
7987 endinpos = startinpos+1;
7988 if (unicode_decode_call_errorhandler_writer(
7989 errors, &errorHandler,
7990 "charmap", "character maps to <undefined>",
7991 &starts, &e, &startinpos, &endinpos, &exc, &s,
7992 writer)) {
7993 goto onError;
7994 }
7995 continue;
7996 }
7997
7998 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7999 goto onError;
8000 ++s;
8001 }
8002 Py_XDECREF(errorHandler);
8003 Py_XDECREF(exc);
8004 return 0;
8005
8006onError:
8007 Py_XDECREF(errorHandler);
8008 Py_XDECREF(exc);
8009 return -1;
8010}
8011
8012static int
8013charmap_decode_mapping(const char *s,
8014 Py_ssize_t size,
8015 PyObject *mapping,
8016 const char *errors,
8017 _PyUnicodeWriter *writer)
8018{
8019 const char *starts = s;
8020 const char *e;
8021 Py_ssize_t startinpos, endinpos;
8022 PyObject *errorHandler = NULL, *exc = NULL;
8023 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02008024 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02008025
8026 e = s + size;
8027
8028 while (s < e) {
8029 ch = *s;
8030
8031 /* Get mapping (char ordinal -> integer, Unicode char or None) */
8032 key = PyLong_FromLong((long)ch);
8033 if (key == NULL)
8034 goto onError;
8035
8036 item = PyObject_GetItem(mapping, key);
8037 Py_DECREF(key);
8038 if (item == NULL) {
8039 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8040 /* No mapping found means: mapping is undefined. */
8041 PyErr_Clear();
8042 goto Undefined;
8043 } else
8044 goto onError;
8045 }
8046
8047 /* Apply mapping */
8048 if (item == Py_None)
8049 goto Undefined;
8050 if (PyLong_Check(item)) {
8051 long value = PyLong_AS_LONG(item);
8052 if (value == 0xFFFE)
8053 goto Undefined;
8054 if (value < 0 || value > MAX_UNICODE) {
8055 PyErr_Format(PyExc_TypeError,
8056 "character mapping must be in range(0x%lx)",
8057 (unsigned long)MAX_UNICODE + 1);
8058 goto onError;
8059 }
8060
8061 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8062 goto onError;
8063 }
8064 else if (PyUnicode_Check(item)) {
8065 if (PyUnicode_READY(item) == -1)
8066 goto onError;
8067 if (PyUnicode_GET_LENGTH(item) == 1) {
8068 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8069 if (value == 0xFFFE)
8070 goto Undefined;
8071 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8072 goto onError;
8073 }
8074 else {
8075 writer->overallocate = 1;
8076 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8077 goto onError;
8078 }
8079 }
8080 else {
8081 /* wrong return value */
8082 PyErr_SetString(PyExc_TypeError,
8083 "character mapping must return integer, None or str");
8084 goto onError;
8085 }
8086 Py_CLEAR(item);
8087 ++s;
8088 continue;
8089
8090Undefined:
8091 /* undefined mapping */
8092 Py_CLEAR(item);
8093 startinpos = s-starts;
8094 endinpos = startinpos+1;
8095 if (unicode_decode_call_errorhandler_writer(
8096 errors, &errorHandler,
8097 "charmap", "character maps to <undefined>",
8098 &starts, &e, &startinpos, &endinpos, &exc, &s,
8099 writer)) {
8100 goto onError;
8101 }
8102 }
8103 Py_XDECREF(errorHandler);
8104 Py_XDECREF(exc);
8105 return 0;
8106
8107onError:
8108 Py_XDECREF(item);
8109 Py_XDECREF(errorHandler);
8110 Py_XDECREF(exc);
8111 return -1;
8112}
8113
Alexander Belopolsky40018472011-02-26 01:02:56 +00008114PyObject *
8115PyUnicode_DecodeCharmap(const char *s,
8116 Py_ssize_t size,
8117 PyObject *mapping,
8118 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008119{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008120 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008121
Guido van Rossumd57fd912000-03-10 22:53:23 +00008122 /* Default to Latin-1 */
8123 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008125
Guido van Rossumd57fd912000-03-10 22:53:23 +00008126 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008127 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008128 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008129 writer.min_length = size;
8130 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008131 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008132
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008133 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008134 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8135 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008136 }
8137 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008138 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8139 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008140 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008141 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008142
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008144 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008145 return NULL;
8146}
8147
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008148/* Charmap encoding: the lookup table */
8149
Alexander Belopolsky40018472011-02-26 01:02:56 +00008150struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008151 PyObject_HEAD
8152 unsigned char level1[32];
8153 int count2, count3;
8154 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008155};
8156
8157static PyObject*
8158encoding_map_size(PyObject *obj, PyObject* args)
8159{
8160 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008161 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008163}
8164
8165static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008166 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 PyDoc_STR("Return the size (in bytes) of this object") },
8168 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008169};
8170
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008172 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008173 "EncodingMap", /*tp_name*/
8174 sizeof(struct encoding_map), /*tp_basicsize*/
8175 0, /*tp_itemsize*/
8176 /* methods */
Inada Naoki7d408692019-05-29 17:23:27 +09008177 0, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02008178 0, /*tp_vectorcall_offset*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 0, /*tp_getattr*/
8180 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02008181 0, /*tp_as_async*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008182 0, /*tp_repr*/
8183 0, /*tp_as_number*/
8184 0, /*tp_as_sequence*/
8185 0, /*tp_as_mapping*/
8186 0, /*tp_hash*/
8187 0, /*tp_call*/
8188 0, /*tp_str*/
8189 0, /*tp_getattro*/
8190 0, /*tp_setattro*/
8191 0, /*tp_as_buffer*/
8192 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8193 0, /*tp_doc*/
8194 0, /*tp_traverse*/
8195 0, /*tp_clear*/
8196 0, /*tp_richcompare*/
8197 0, /*tp_weaklistoffset*/
8198 0, /*tp_iter*/
8199 0, /*tp_iternext*/
8200 encoding_map_methods, /*tp_methods*/
8201 0, /*tp_members*/
8202 0, /*tp_getset*/
8203 0, /*tp_base*/
8204 0, /*tp_dict*/
8205 0, /*tp_descr_get*/
8206 0, /*tp_descr_set*/
8207 0, /*tp_dictoffset*/
8208 0, /*tp_init*/
8209 0, /*tp_alloc*/
8210 0, /*tp_new*/
8211 0, /*tp_free*/
8212 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008213};
8214
8215PyObject*
8216PyUnicode_BuildEncodingMap(PyObject* string)
8217{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008218 PyObject *result;
8219 struct encoding_map *mresult;
8220 int i;
8221 int need_dict = 0;
8222 unsigned char level1[32];
8223 unsigned char level2[512];
8224 unsigned char *mlevel1, *mlevel2, *mlevel3;
8225 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008226 int kind;
8227 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008228 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008229 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008230
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008231 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008232 PyErr_BadArgument();
8233 return NULL;
8234 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008235 kind = PyUnicode_KIND(string);
8236 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008237 length = PyUnicode_GET_LENGTH(string);
8238 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008239 memset(level1, 0xFF, sizeof level1);
8240 memset(level2, 0xFF, sizeof level2);
8241
8242 /* If there isn't a one-to-one mapping of NULL to \0,
8243 or if there are non-BMP characters, we need to use
8244 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008245 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008246 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008247 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008248 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008249 ch = PyUnicode_READ(kind, data, i);
8250 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008251 need_dict = 1;
8252 break;
8253 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008254 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008255 /* unmapped character */
8256 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008257 l1 = ch >> 11;
8258 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008259 if (level1[l1] == 0xFF)
8260 level1[l1] = count2++;
8261 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008262 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008263 }
8264
8265 if (count2 >= 0xFF || count3 >= 0xFF)
8266 need_dict = 1;
8267
8268 if (need_dict) {
8269 PyObject *result = PyDict_New();
8270 PyObject *key, *value;
8271 if (!result)
8272 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008273 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008274 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008275 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008276 if (!key || !value)
8277 goto failed1;
8278 if (PyDict_SetItem(result, key, value) == -1)
8279 goto failed1;
8280 Py_DECREF(key);
8281 Py_DECREF(value);
8282 }
8283 return result;
8284 failed1:
8285 Py_XDECREF(key);
8286 Py_XDECREF(value);
8287 Py_DECREF(result);
8288 return NULL;
8289 }
8290
8291 /* Create a three-level trie */
8292 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8293 16*count2 + 128*count3 - 1);
8294 if (!result)
8295 return PyErr_NoMemory();
8296 PyObject_Init(result, &EncodingMapType);
8297 mresult = (struct encoding_map*)result;
8298 mresult->count2 = count2;
8299 mresult->count3 = count3;
8300 mlevel1 = mresult->level1;
8301 mlevel2 = mresult->level23;
8302 mlevel3 = mresult->level23 + 16*count2;
8303 memcpy(mlevel1, level1, 32);
8304 memset(mlevel2, 0xFF, 16*count2);
8305 memset(mlevel3, 0, 128*count3);
8306 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008307 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008308 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008309 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8310 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008311 /* unmapped character */
8312 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008313 o1 = ch>>11;
8314 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008315 i2 = 16*mlevel1[o1] + o2;
8316 if (mlevel2[i2] == 0xFF)
8317 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008318 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008319 i3 = 128*mlevel2[i2] + o3;
8320 mlevel3[i3] = i;
8321 }
8322 return result;
8323}
8324
8325static int
Victor Stinner22168992011-11-20 17:09:18 +01008326encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008327{
8328 struct encoding_map *map = (struct encoding_map*)mapping;
8329 int l1 = c>>11;
8330 int l2 = (c>>7) & 0xF;
8331 int l3 = c & 0x7F;
8332 int i;
8333
Victor Stinner22168992011-11-20 17:09:18 +01008334 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008336 if (c == 0)
8337 return 0;
8338 /* level 1*/
8339 i = map->level1[l1];
8340 if (i == 0xFF) {
8341 return -1;
8342 }
8343 /* level 2*/
8344 i = map->level23[16*i+l2];
8345 if (i == 0xFF) {
8346 return -1;
8347 }
8348 /* level 3 */
8349 i = map->level23[16*map->count2 + 128*i + l3];
8350 if (i == 0) {
8351 return -1;
8352 }
8353 return i;
8354}
8355
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356/* Lookup the character ch in the mapping. If the character
8357 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008358 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008359static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008360charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008361{
Christian Heimes217cfd12007-12-02 14:31:20 +00008362 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363 PyObject *x;
8364
8365 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367 x = PyObject_GetItem(mapping, w);
8368 Py_DECREF(w);
8369 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008370 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8371 /* No mapping found means: mapping is undefined. */
8372 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008373 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008374 } else
8375 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008376 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008377 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008379 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 long value = PyLong_AS_LONG(x);
8381 if (value < 0 || value > 255) {
8382 PyErr_SetString(PyExc_TypeError,
8383 "character mapping must be in range(256)");
8384 Py_DECREF(x);
8385 return NULL;
8386 }
8387 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008388 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008389 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 /* wrong return value */
8393 PyErr_Format(PyExc_TypeError,
8394 "character mapping must return integer, bytes or None, not %.400s",
8395 x->ob_type->tp_name);
8396 Py_DECREF(x);
8397 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008398 }
8399}
8400
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008401static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008402charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008403{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008404 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8405 /* exponentially overallocate to minimize reallocations */
8406 if (requiredsize < 2*outsize)
8407 requiredsize = 2*outsize;
8408 if (_PyBytes_Resize(outobj, requiredsize))
8409 return -1;
8410 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008411}
8412
Benjamin Peterson14339b62009-01-31 16:36:08 +00008413typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008415} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008417 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008418 space is available. Return a new reference to the object that
8419 was put in the output buffer, or Py_None, if the mapping was undefined
8420 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008421 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008422static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008423charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008424 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008426 PyObject *rep;
8427 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008428 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429
Christian Heimes90aa7642007-12-19 02:45:37 +00008430 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008431 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008432 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008433 if (res == -1)
8434 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008435 if (outsize<requiredsize)
8436 if (charmapencode_resize(outobj, outpos, requiredsize))
8437 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008438 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 outstart[(*outpos)++] = (char)res;
8440 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008441 }
8442
8443 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008444 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008446 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 Py_DECREF(rep);
8448 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008449 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008450 if (PyLong_Check(rep)) {
8451 Py_ssize_t requiredsize = *outpos+1;
8452 if (outsize<requiredsize)
8453 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8454 Py_DECREF(rep);
8455 return enc_EXCEPTION;
8456 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008457 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008459 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 else {
8461 const char *repchars = PyBytes_AS_STRING(rep);
8462 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8463 Py_ssize_t requiredsize = *outpos+repsize;
8464 if (outsize<requiredsize)
8465 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8466 Py_DECREF(rep);
8467 return enc_EXCEPTION;
8468 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008469 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 memcpy(outstart + *outpos, repchars, repsize);
8471 *outpos += repsize;
8472 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008473 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008474 Py_DECREF(rep);
8475 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008476}
8477
8478/* handle an error in PyUnicode_EncodeCharmap
8479 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008480static int
8481charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008482 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008484 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008485 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008486{
8487 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008488 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008489 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008490 enum PyUnicode_Kind kind;
8491 void *data;
8492 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008494 Py_ssize_t collstartpos = *inpos;
8495 Py_ssize_t collendpos = *inpos+1;
8496 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008497 const char *encoding = "charmap";
8498 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008499 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008500 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008501 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502
Benjamin Petersonbac79492012-01-14 13:34:47 -05008503 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008504 return -1;
8505 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506 /* find all unencodable characters */
8507 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008508 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008509 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008510 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008511 val = encoding_map_lookup(ch, mapping);
8512 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 break;
8514 ++collendpos;
8515 continue;
8516 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008517
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008518 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8519 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 if (rep==NULL)
8521 return -1;
8522 else if (rep!=Py_None) {
8523 Py_DECREF(rep);
8524 break;
8525 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008526 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008527 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008528 }
8529 /* cache callback name lookup
8530 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008531 if (*error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02008532 *error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02008533
8534 switch (*error_handler) {
8535 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008536 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008537 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008538
8539 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008540 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008541 x = charmapencode_output('?', mapping, res, respos);
8542 if (x==enc_EXCEPTION) {
8543 return -1;
8544 }
8545 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008546 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 return -1;
8548 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008549 }
8550 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008551 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008552 *inpos = collendpos;
8553 break;
Victor Stinner50149202015-09-22 00:26:54 +02008554
8555 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008556 /* generate replacement (temporarily (mis)uses p) */
8557 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 char buffer[2+29+1+1];
8559 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008560 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008561 for (cp = buffer; *cp; ++cp) {
8562 x = charmapencode_output(*cp, mapping, res, respos);
8563 if (x==enc_EXCEPTION)
8564 return -1;
8565 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008566 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 return -1;
8568 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008569 }
8570 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008571 *inpos = collendpos;
8572 break;
Victor Stinner50149202015-09-22 00:26:54 +02008573
Benjamin Peterson14339b62009-01-31 16:36:08 +00008574 default:
Victor Stinner50149202015-09-22 00:26:54 +02008575 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008576 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008577 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008578 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008580 if (PyBytes_Check(repunicode)) {
8581 /* Directly copy bytes result to output. */
8582 Py_ssize_t outsize = PyBytes_Size(*res);
8583 Py_ssize_t requiredsize;
8584 repsize = PyBytes_Size(repunicode);
8585 requiredsize = *respos + repsize;
8586 if (requiredsize > outsize)
8587 /* Make room for all additional bytes. */
8588 if (charmapencode_resize(res, respos, requiredsize)) {
8589 Py_DECREF(repunicode);
8590 return -1;
8591 }
8592 memcpy(PyBytes_AsString(*res) + *respos,
8593 PyBytes_AsString(repunicode), repsize);
8594 *respos += repsize;
8595 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008596 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008597 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008598 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008599 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008600 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008601 Py_DECREF(repunicode);
8602 return -1;
8603 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008604 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008605 data = PyUnicode_DATA(repunicode);
8606 kind = PyUnicode_KIND(repunicode);
8607 for (index = 0; index < repsize; index++) {
8608 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8609 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008611 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 return -1;
8613 }
8614 else if (x==enc_FAILED) {
8615 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008616 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 return -1;
8618 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008619 }
8620 *inpos = newpos;
8621 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622 }
8623 return 0;
8624}
8625
Alexander Belopolsky40018472011-02-26 01:02:56 +00008626PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008627_PyUnicode_EncodeCharmap(PyObject *unicode,
8628 PyObject *mapping,
8629 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008630{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008631 /* output object */
8632 PyObject *res = NULL;
8633 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008634 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008635 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008636 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008637 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008638 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008640 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008641 void *data;
8642 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008643
Benjamin Petersonbac79492012-01-14 13:34:47 -05008644 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008645 return NULL;
8646 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008647 data = PyUnicode_DATA(unicode);
8648 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008649
Guido van Rossumd57fd912000-03-10 22:53:23 +00008650 /* Default to Latin-1 */
8651 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008652 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008653
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008654 /* allocate enough for a simple encoding without
8655 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008656 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008657 if (res == NULL)
8658 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008659 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008660 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008661
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008662 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008663 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008665 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008666 if (x==enc_EXCEPTION) /* error */
8667 goto onError;
8668 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008669 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008670 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008671 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008672 &res, &respos)) {
8673 goto onError;
8674 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008675 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 else
8677 /* done with this character => adjust input position */
8678 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008679 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008680
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008681 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008682 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008683 if (_PyBytes_Resize(&res, respos) < 0)
8684 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008685
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008687 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688 return res;
8689
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 Py_XDECREF(res);
8692 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008693 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008694 return NULL;
8695}
8696
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008697/* Deprecated */
8698PyObject *
8699PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8700 Py_ssize_t size,
8701 PyObject *mapping,
8702 const char *errors)
8703{
8704 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008705 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008706 if (unicode == NULL)
8707 return NULL;
8708 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8709 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008710 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008711}
8712
Alexander Belopolsky40018472011-02-26 01:02:56 +00008713PyObject *
8714PyUnicode_AsCharmapString(PyObject *unicode,
8715 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008716{
8717 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 PyErr_BadArgument();
8719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008720 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008721 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008722}
8723
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008724/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008725static void
8726make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008728 Py_ssize_t startpos, Py_ssize_t endpos,
8729 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008730{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008731 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 *exceptionObject = _PyUnicodeTranslateError_Create(
8733 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008734 }
8735 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8737 goto onError;
8738 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8739 goto onError;
8740 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8741 goto onError;
8742 return;
8743 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008744 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008745 }
8746}
8747
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008748/* error handling callback helper:
8749 build arguments, call the callback and check the arguments,
8750 put the result into newpos and return the replacement string, which
8751 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008752static PyObject *
8753unicode_translate_call_errorhandler(const char *errors,
8754 PyObject **errorHandler,
8755 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008756 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008757 Py_ssize_t startpos, Py_ssize_t endpos,
8758 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008759{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008760 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008761
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008762 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008763 PyObject *restuple;
8764 PyObject *resunicode;
8765
8766 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008768 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008769 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008770 }
8771
8772 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008774 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008775 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008776
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008777 restuple = PyObject_CallFunctionObjArgs(
8778 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008779 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008780 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008781 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008782 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 Py_DECREF(restuple);
8784 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008785 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008786 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008787 &resunicode, &i_newpos)) {
8788 Py_DECREF(restuple);
8789 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008790 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008791 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008793 else
8794 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008796 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008797 Py_DECREF(restuple);
8798 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008799 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008800 Py_INCREF(resunicode);
8801 Py_DECREF(restuple);
8802 return resunicode;
8803}
8804
8805/* Lookup the character ch in the mapping and put the result in result,
8806 which must be decrefed by the caller.
8807 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008808static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008809charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008810{
Christian Heimes217cfd12007-12-02 14:31:20 +00008811 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008812 PyObject *x;
8813
8814 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008815 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008816 x = PyObject_GetItem(mapping, w);
8817 Py_DECREF(w);
8818 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008819 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8820 /* No mapping found means: use 1:1 mapping. */
8821 PyErr_Clear();
8822 *result = NULL;
8823 return 0;
8824 } else
8825 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008826 }
8827 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008828 *result = x;
8829 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008830 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008831 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008832 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008833 if (value < 0 || value > MAX_UNICODE) {
8834 PyErr_Format(PyExc_ValueError,
8835 "character mapping must be in range(0x%x)",
8836 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008837 Py_DECREF(x);
8838 return -1;
8839 }
8840 *result = x;
8841 return 0;
8842 }
8843 else if (PyUnicode_Check(x)) {
8844 *result = x;
8845 return 0;
8846 }
8847 else {
8848 /* wrong return value */
8849 PyErr_SetString(PyExc_TypeError,
8850 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008851 Py_DECREF(x);
8852 return -1;
8853 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008854}
Victor Stinner1194ea02014-04-04 19:37:40 +02008855
8856/* lookup the character, write the result into the writer.
8857 Return 1 if the result was written into the writer, return 0 if the mapping
8858 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008859static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008860charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8861 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008862{
Victor Stinner1194ea02014-04-04 19:37:40 +02008863 PyObject *item;
8864
8865 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008866 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008867
8868 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008869 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008870 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008872 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008873 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008874 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008875
8876 if (item == Py_None) {
8877 Py_DECREF(item);
8878 return 0;
8879 }
8880
8881 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008882 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8883 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8884 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008885 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8886 Py_DECREF(item);
8887 return -1;
8888 }
8889 Py_DECREF(item);
8890 return 1;
8891 }
8892
8893 if (!PyUnicode_Check(item)) {
8894 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008895 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008896 }
8897
8898 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8899 Py_DECREF(item);
8900 return -1;
8901 }
8902
8903 Py_DECREF(item);
8904 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008905}
8906
Victor Stinner89a76ab2014-04-05 11:44:04 +02008907static int
8908unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8909 Py_UCS1 *translate)
8910{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008911 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008912 int ret = 0;
8913
Victor Stinner89a76ab2014-04-05 11:44:04 +02008914 if (charmaptranslate_lookup(ch, mapping, &item)) {
8915 return -1;
8916 }
8917
8918 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008919 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008920 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008921 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008922 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008923 /* not found => default to 1:1 mapping */
8924 translate[ch] = ch;
8925 return 1;
8926 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008927 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008928 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008929 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8930 used it */
8931 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008932 /* invalid character or character outside ASCII:
8933 skip the fast translate */
8934 goto exit;
8935 }
8936 translate[ch] = (Py_UCS1)replace;
8937 }
8938 else if (PyUnicode_Check(item)) {
8939 Py_UCS4 replace;
8940
8941 if (PyUnicode_READY(item) == -1) {
8942 Py_DECREF(item);
8943 return -1;
8944 }
8945 if (PyUnicode_GET_LENGTH(item) != 1)
8946 goto exit;
8947
8948 replace = PyUnicode_READ_CHAR(item, 0);
8949 if (replace > 127)
8950 goto exit;
8951 translate[ch] = (Py_UCS1)replace;
8952 }
8953 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008954 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008955 goto exit;
8956 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008957 ret = 1;
8958
Benjamin Peterson1365de72014-04-07 20:15:41 -04008959 exit:
8960 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008961 return ret;
8962}
8963
8964/* Fast path for ascii => ascii translation. Return 1 if the whole string
8965 was translated into writer, return 0 if the input string was partially
8966 translated into writer, raise an exception and return -1 on error. */
8967static int
8968unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008969 _PyUnicodeWriter *writer, int ignore,
8970 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008971{
Victor Stinner872b2912014-04-05 14:27:07 +02008972 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008973 Py_ssize_t len;
8974 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008975 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008976
Victor Stinner89a76ab2014-04-05 11:44:04 +02008977 len = PyUnicode_GET_LENGTH(input);
8978
Victor Stinner872b2912014-04-05 14:27:07 +02008979 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008980
8981 in = PyUnicode_1BYTE_DATA(input);
8982 end = in + len;
8983
8984 assert(PyUnicode_IS_ASCII(writer->buffer));
8985 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8986 out = PyUnicode_1BYTE_DATA(writer->buffer);
8987
Victor Stinner872b2912014-04-05 14:27:07 +02008988 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008989 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008990 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008991 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008992 int translate = unicode_fast_translate_lookup(mapping, ch,
8993 ascii_table);
8994 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008995 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008996 if (translate == 0)
8997 goto exit;
8998 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008999 }
Victor Stinner872b2912014-04-05 14:27:07 +02009000 if (ch2 == 0xfe) {
9001 if (ignore)
9002 continue;
9003 goto exit;
9004 }
9005 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009006 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02009007 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009008 }
Victor Stinner872b2912014-04-05 14:27:07 +02009009 res = 1;
9010
9011exit:
9012 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01009013 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02009014 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009015}
9016
Victor Stinner3222da22015-10-01 22:07:32 +02009017static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009018_PyUnicode_TranslateCharmap(PyObject *input,
9019 PyObject *mapping,
9020 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009022 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02009023 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024 Py_ssize_t size, i;
9025 int kind;
9026 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02009027 _PyUnicodeWriter writer;
9028 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02009029 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009030 PyObject *errorHandler = NULL;
9031 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009032 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009033 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009034
Guido van Rossumd57fd912000-03-10 22:53:23 +00009035 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009036 PyErr_BadArgument();
9037 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040 if (PyUnicode_READY(input) == -1)
9041 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009042 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009043 kind = PyUnicode_KIND(input);
9044 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009045
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009046 if (size == 0)
9047 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009048
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009049 /* allocate enough for a simple 1:1 translation without
9050 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02009051 _PyUnicodeWriter_Init(&writer);
9052 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009053 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009054
Victor Stinner872b2912014-04-05 14:27:07 +02009055 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9056
Victor Stinner33798672016-03-01 21:59:58 +01009057 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009058 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01009059 if (PyUnicode_IS_ASCII(input)) {
9060 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9061 if (res < 0) {
9062 _PyUnicodeWriter_Dealloc(&writer);
9063 return NULL;
9064 }
9065 if (res == 1)
9066 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009067 }
Victor Stinner33798672016-03-01 21:59:58 +01009068 else {
9069 i = 0;
9070 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009071
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009073 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009074 int translate;
9075 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9076 Py_ssize_t newpos;
9077 /* startpos for collecting untranslatable chars */
9078 Py_ssize_t collstart;
9079 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009080 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009081
Victor Stinner1194ea02014-04-04 19:37:40 +02009082 ch = PyUnicode_READ(kind, data, i);
9083 translate = charmaptranslate_output(ch, mapping, &writer);
9084 if (translate < 0)
9085 goto onError;
9086
9087 if (translate != 0) {
9088 /* it worked => adjust input pointer */
9089 ++i;
9090 continue;
9091 }
9092
9093 /* untranslatable character */
9094 collstart = i;
9095 collend = i+1;
9096
9097 /* find all untranslatable characters */
9098 while (collend < size) {
9099 PyObject *x;
9100 ch = PyUnicode_READ(kind, data, collend);
9101 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009102 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009103 Py_XDECREF(x);
9104 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009105 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009106 ++collend;
9107 }
9108
9109 if (ignore) {
9110 i = collend;
9111 }
9112 else {
9113 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9114 reason, input, &exc,
9115 collstart, collend, &newpos);
9116 if (repunicode == NULL)
9117 goto onError;
9118 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009119 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009120 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009121 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009122 Py_DECREF(repunicode);
9123 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009124 }
9125 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009126 Py_XDECREF(exc);
9127 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009128 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009129
Benjamin Peterson29060642009-01-31 22:14:21 +00009130 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009131 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009132 Py_XDECREF(exc);
9133 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009134 return NULL;
9135}
9136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009137/* Deprecated. Use PyUnicode_Translate instead. */
9138PyObject *
9139PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9140 Py_ssize_t size,
9141 PyObject *mapping,
9142 const char *errors)
9143{
Christian Heimes5f520f42012-09-11 14:03:25 +02009144 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009145 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 if (!unicode)
9147 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009148 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9149 Py_DECREF(unicode);
9150 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009151}
9152
Alexander Belopolsky40018472011-02-26 01:02:56 +00009153PyObject *
9154PyUnicode_Translate(PyObject *str,
9155 PyObject *mapping,
9156 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009157{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009158 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009159 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009160 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009161}
Tim Petersced69f82003-09-16 20:30:58 +00009162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009163PyObject *
9164_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9165{
9166 if (!PyUnicode_Check(unicode)) {
9167 PyErr_BadInternalCall();
9168 return NULL;
9169 }
9170 if (PyUnicode_READY(unicode) == -1)
9171 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009172 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009173 /* If the string is already ASCII, just return the same string */
9174 Py_INCREF(unicode);
9175 return unicode;
9176 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009177
9178 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9179 PyObject *result = PyUnicode_New(len, 127);
9180 if (result == NULL) {
9181 return NULL;
9182 }
9183
9184 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9185 int kind = PyUnicode_KIND(unicode);
9186 const void *data = PyUnicode_DATA(unicode);
9187 Py_ssize_t i;
9188 for (i = 0; i < len; ++i) {
9189 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9190 if (ch < 127) {
9191 out[i] = ch;
9192 }
9193 else if (Py_UNICODE_ISSPACE(ch)) {
9194 out[i] = ' ';
9195 }
9196 else {
9197 int decimal = Py_UNICODE_TODECIMAL(ch);
9198 if (decimal < 0) {
9199 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009200 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009201 _PyUnicode_LENGTH(result) = i + 1;
9202 break;
9203 }
9204 out[i] = '0' + decimal;
9205 }
9206 }
9207
INADA Naoki16dfca42018-07-14 12:06:43 +09009208 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009209 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210}
9211
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009212PyObject *
9213PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9214 Py_ssize_t length)
9215{
Victor Stinnerf0124502011-11-21 23:12:56 +01009216 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009217 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009218 Py_UCS4 maxchar;
9219 enum PyUnicode_Kind kind;
9220 void *data;
9221
Victor Stinner99d7ad02012-02-22 13:37:39 +01009222 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009223 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009224 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009225 if (ch > 127) {
9226 int decimal = Py_UNICODE_TODECIMAL(ch);
9227 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009228 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009229 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009230 }
9231 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009232
9233 /* Copy to a new string */
9234 decimal = PyUnicode_New(length, maxchar);
9235 if (decimal == NULL)
9236 return decimal;
9237 kind = PyUnicode_KIND(decimal);
9238 data = PyUnicode_DATA(decimal);
9239 /* Iterate over code points */
9240 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009241 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009242 if (ch > 127) {
9243 int decimal = Py_UNICODE_TODECIMAL(ch);
9244 if (decimal >= 0)
9245 ch = '0' + decimal;
9246 }
9247 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009248 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009249 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009250}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009251/* --- Decimal Encoder ---------------------------------------------------- */
9252
Alexander Belopolsky40018472011-02-26 01:02:56 +00009253int
9254PyUnicode_EncodeDecimal(Py_UNICODE *s,
9255 Py_ssize_t length,
9256 char *output,
9257 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009258{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009259 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009260 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009261 enum PyUnicode_Kind kind;
9262 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009263
9264 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009265 PyErr_BadArgument();
9266 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009267 }
9268
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009269 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009270 if (unicode == NULL)
9271 return -1;
9272
Victor Stinner42bf7752011-11-21 22:52:58 +01009273 kind = PyUnicode_KIND(unicode);
9274 data = PyUnicode_DATA(unicode);
9275
Victor Stinnerb84d7232011-11-22 01:50:07 +01009276 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009277 PyObject *exc;
9278 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009279 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009280 Py_ssize_t startpos;
9281
9282 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009283
Benjamin Peterson29060642009-01-31 22:14:21 +00009284 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009285 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009286 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009287 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009288 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009289 decimal = Py_UNICODE_TODECIMAL(ch);
9290 if (decimal >= 0) {
9291 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009292 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009293 continue;
9294 }
9295 if (0 < ch && ch < 256) {
9296 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009297 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009298 continue;
9299 }
Victor Stinner6345be92011-11-25 20:09:01 +01009300
Victor Stinner42bf7752011-11-21 22:52:58 +01009301 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009302 exc = NULL;
9303 raise_encode_exception(&exc, "decimal", unicode,
9304 startpos, startpos+1,
9305 "invalid decimal Unicode string");
9306 Py_XDECREF(exc);
9307 Py_DECREF(unicode);
9308 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009309 }
9310 /* 0-terminate the output string */
9311 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009312 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009313 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009314}
9315
Guido van Rossumd57fd912000-03-10 22:53:23 +00009316/* --- Helpers ------------------------------------------------------------ */
9317
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009318/* helper macro to fixup start/end slice values */
9319#define ADJUST_INDICES(start, end, len) \
9320 if (end > len) \
9321 end = len; \
9322 else if (end < 0) { \
9323 end += len; \
9324 if (end < 0) \
9325 end = 0; \
9326 } \
9327 if (start < 0) { \
9328 start += len; \
9329 if (start < 0) \
9330 start = 0; \
9331 }
9332
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009333static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009334any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009335 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009336 Py_ssize_t end,
9337 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009339 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009340 void *buf1, *buf2;
9341 Py_ssize_t len1, len2, result;
9342
9343 kind1 = PyUnicode_KIND(s1);
9344 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009345 if (kind1 < kind2)
9346 return -1;
9347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 len1 = PyUnicode_GET_LENGTH(s1);
9349 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009350 ADJUST_INDICES(start, end, len1);
9351 if (end - start < len2)
9352 return -1;
9353
9354 buf1 = PyUnicode_DATA(s1);
9355 buf2 = PyUnicode_DATA(s2);
9356 if (len2 == 1) {
9357 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9358 result = findchar((const char *)buf1 + kind1*start,
9359 kind1, end - start, ch, direction);
9360 if (result == -1)
9361 return -1;
9362 else
9363 return start + result;
9364 }
9365
9366 if (kind2 != kind1) {
9367 buf2 = _PyUnicode_AsKind(s2, kind1);
9368 if (!buf2)
9369 return -2;
9370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009371
Victor Stinner794d5672011-10-10 03:21:36 +02009372 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009373 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009374 case PyUnicode_1BYTE_KIND:
9375 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9376 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9377 else
9378 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9379 break;
9380 case PyUnicode_2BYTE_KIND:
9381 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9382 break;
9383 case PyUnicode_4BYTE_KIND:
9384 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9385 break;
9386 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009387 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009388 }
9389 }
9390 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009391 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009392 case PyUnicode_1BYTE_KIND:
9393 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9394 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9395 else
9396 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9397 break;
9398 case PyUnicode_2BYTE_KIND:
9399 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9400 break;
9401 case PyUnicode_4BYTE_KIND:
9402 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9403 break;
9404 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009405 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009406 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 }
9408
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009409 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009410 PyMem_Free(buf2);
9411
9412 return result;
9413}
9414
Victor Stinner59423e32018-11-26 13:40:01 +01009415/* _PyUnicode_InsertThousandsGrouping() helper functions */
9416#include "stringlib/localeutil.h"
9417
9418/**
9419 * InsertThousandsGrouping:
9420 * @writer: Unicode writer.
9421 * @n_buffer: Number of characters in @buffer.
9422 * @digits: Digits we're reading from. If count is non-NULL, this is unused.
9423 * @d_pos: Start of digits string.
9424 * @n_digits: The number of digits in the string, in which we want
9425 * to put the grouping chars.
9426 * @min_width: The minimum width of the digits in the output string.
9427 * Output will be zero-padded on the left to fill.
9428 * @grouping: see definition in localeconv().
9429 * @thousands_sep: see definition in localeconv().
9430 *
9431 * There are 2 modes: counting and filling. If @writer is NULL,
9432 * we are in counting mode, else filling mode.
9433 * If counting, the required buffer size is returned.
9434 * If filling, we know the buffer will be large enough, so we don't
9435 * need to pass in the buffer size.
9436 * Inserts thousand grouping characters (as defined by grouping and
9437 * thousands_sep) into @writer.
9438 *
9439 * Return value: -1 on error, number of characters otherwise.
9440 **/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009442_PyUnicode_InsertThousandsGrouping(
Victor Stinner59423e32018-11-26 13:40:01 +01009443 _PyUnicodeWriter *writer,
Victor Stinner41a863c2012-02-24 00:37:51 +01009444 Py_ssize_t n_buffer,
Victor Stinner59423e32018-11-26 13:40:01 +01009445 PyObject *digits,
9446 Py_ssize_t d_pos,
9447 Py_ssize_t n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009448 Py_ssize_t min_width,
Victor Stinner59423e32018-11-26 13:40:01 +01009449 const char *grouping,
9450 PyObject *thousands_sep,
Victor Stinner41a863c2012-02-24 00:37:51 +01009451 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452{
Xtreak3f7983a2019-01-07 20:39:14 +05309453 min_width = Py_MAX(0, min_width);
Victor Stinner59423e32018-11-26 13:40:01 +01009454 if (writer) {
9455 assert(digits != NULL);
9456 assert(maxchar == NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009457 }
9458 else {
Victor Stinner59423e32018-11-26 13:40:01 +01009459 assert(digits == NULL);
9460 assert(maxchar != NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009461 }
Victor Stinner59423e32018-11-26 13:40:01 +01009462 assert(0 <= d_pos);
9463 assert(0 <= n_digits);
Victor Stinner59423e32018-11-26 13:40:01 +01009464 assert(grouping != NULL);
9465
9466 if (digits != NULL) {
9467 if (PyUnicode_READY(digits) == -1) {
9468 return -1;
Victor Stinner90f50d42012-02-24 01:44:47 +01009469 }
Victor Stinner59423e32018-11-26 13:40:01 +01009470 }
9471 if (PyUnicode_READY(thousands_sep) == -1) {
9472 return -1;
Victor Stinner41a863c2012-02-24 00:37:51 +01009473 }
9474
Victor Stinner59423e32018-11-26 13:40:01 +01009475 Py_ssize_t count = 0;
9476 Py_ssize_t n_zeros;
9477 int loop_broken = 0;
9478 int use_separator = 0; /* First time through, don't append the
9479 separator. They only go between
9480 groups. */
9481 Py_ssize_t buffer_pos;
9482 Py_ssize_t digits_pos;
9483 Py_ssize_t len;
9484 Py_ssize_t n_chars;
9485 Py_ssize_t remaining = n_digits; /* Number of chars remaining to
9486 be looked at */
9487 /* A generator that returns all of the grouping widths, until it
9488 returns 0. */
9489 GroupGenerator groupgen;
9490 GroupGenerator_init(&groupgen, grouping);
9491 const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9492
9493 /* if digits are not grouped, thousands separator
9494 should be an empty string */
9495 assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
9496
9497 digits_pos = d_pos + n_digits;
9498 if (writer) {
9499 buffer_pos = writer->pos + n_buffer;
9500 assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
9501 assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009502 }
Victor Stinner59423e32018-11-26 13:40:01 +01009503 else {
9504 buffer_pos = n_buffer;
Victor Stinner90f50d42012-02-24 01:44:47 +01009505 }
Victor Stinner59423e32018-11-26 13:40:01 +01009506
9507 if (!writer) {
Victor Stinner41a863c2012-02-24 00:37:51 +01009508 *maxchar = 127;
Victor Stinner41a863c2012-02-24 00:37:51 +01009509 }
Victor Stinner59423e32018-11-26 13:40:01 +01009510
9511 while ((len = GroupGenerator_next(&groupgen)) > 0) {
9512 len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
9513 n_zeros = Py_MAX(0, len - remaining);
9514 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9515
9516 /* Use n_zero zero's and n_chars chars */
9517
9518 /* Count only, don't do anything. */
9519 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9520
9521 /* Copy into the writer. */
9522 InsertThousandsGrouping_fill(writer, &buffer_pos,
9523 digits, &digits_pos,
9524 n_chars, n_zeros,
9525 use_separator ? thousands_sep : NULL,
9526 thousands_sep_len, maxchar);
9527
9528 /* Use a separator next time. */
9529 use_separator = 1;
9530
9531 remaining -= n_chars;
9532 min_width -= len;
9533
9534 if (remaining <= 0 && min_width <= 0) {
9535 loop_broken = 1;
9536 break;
9537 }
9538 min_width -= thousands_sep_len;
9539 }
9540 if (!loop_broken) {
9541 /* We left the loop without using a break statement. */
9542
9543 len = Py_MAX(Py_MAX(remaining, min_width), 1);
9544 n_zeros = Py_MAX(0, len - remaining);
9545 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9546
9547 /* Use n_zero zero's and n_chars chars */
9548 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9549
9550 /* Copy into the writer. */
9551 InsertThousandsGrouping_fill(writer, &buffer_pos,
9552 digits, &digits_pos,
9553 n_chars, n_zeros,
9554 use_separator ? thousands_sep : NULL,
9555 thousands_sep_len, maxchar);
9556 }
9557 return count;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558}
9559
9560
Alexander Belopolsky40018472011-02-26 01:02:56 +00009561Py_ssize_t
9562PyUnicode_Count(PyObject *str,
9563 PyObject *substr,
9564 Py_ssize_t start,
9565 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009567 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009568 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569 void *buf1 = NULL, *buf2 = NULL;
9570 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009571
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009572 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009573 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009574
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009575 kind1 = PyUnicode_KIND(str);
9576 kind2 = PyUnicode_KIND(substr);
9577 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009578 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009579
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009580 len1 = PyUnicode_GET_LENGTH(str);
9581 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009583 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009584 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009585
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009586 buf1 = PyUnicode_DATA(str);
9587 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009588 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009589 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009590 if (!buf2)
9591 goto onError;
9592 }
9593
9594 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009595 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009596 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009597 result = asciilib_count(
9598 ((Py_UCS1*)buf1) + start, end - start,
9599 buf2, len2, PY_SSIZE_T_MAX
9600 );
9601 else
9602 result = ucs1lib_count(
9603 ((Py_UCS1*)buf1) + start, end - start,
9604 buf2, len2, PY_SSIZE_T_MAX
9605 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009606 break;
9607 case PyUnicode_2BYTE_KIND:
9608 result = ucs2lib_count(
9609 ((Py_UCS2*)buf1) + start, end - start,
9610 buf2, len2, PY_SSIZE_T_MAX
9611 );
9612 break;
9613 case PyUnicode_4BYTE_KIND:
9614 result = ucs4lib_count(
9615 ((Py_UCS4*)buf1) + start, end - start,
9616 buf2, len2, PY_SSIZE_T_MAX
9617 );
9618 break;
9619 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009620 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009621 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009622
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009623 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 PyMem_Free(buf2);
9625
Guido van Rossumd57fd912000-03-10 22:53:23 +00009626 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009628 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009629 PyMem_Free(buf2);
9630 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631}
9632
Alexander Belopolsky40018472011-02-26 01:02:56 +00009633Py_ssize_t
9634PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009635 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009636 Py_ssize_t start,
9637 Py_ssize_t end,
9638 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009639{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009640 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009641 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009642
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009643 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009644}
9645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009646Py_ssize_t
9647PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9648 Py_ssize_t start, Py_ssize_t end,
9649 int direction)
9650{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009652 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 if (PyUnicode_READY(str) == -1)
9654 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009655 len = PyUnicode_GET_LENGTH(str);
9656 ADJUST_INDICES(start, end, len);
9657 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009658 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009659 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009660 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9661 kind, end-start, ch, direction);
9662 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009664 else
9665 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009666}
9667
Alexander Belopolsky40018472011-02-26 01:02:56 +00009668static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009669tailmatch(PyObject *self,
9670 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009671 Py_ssize_t start,
9672 Py_ssize_t end,
9673 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009674{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675 int kind_self;
9676 int kind_sub;
9677 void *data_self;
9678 void *data_sub;
9679 Py_ssize_t offset;
9680 Py_ssize_t i;
9681 Py_ssize_t end_sub;
9682
9683 if (PyUnicode_READY(self) == -1 ||
9684 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009685 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009686
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9688 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009689 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009690 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009691
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009692 if (PyUnicode_GET_LENGTH(substring) == 0)
9693 return 1;
9694
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009695 kind_self = PyUnicode_KIND(self);
9696 data_self = PyUnicode_DATA(self);
9697 kind_sub = PyUnicode_KIND(substring);
9698 data_sub = PyUnicode_DATA(substring);
9699 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9700
9701 if (direction > 0)
9702 offset = end;
9703 else
9704 offset = start;
9705
9706 if (PyUnicode_READ(kind_self, data_self, offset) ==
9707 PyUnicode_READ(kind_sub, data_sub, 0) &&
9708 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9709 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9710 /* If both are of the same kind, memcmp is sufficient */
9711 if (kind_self == kind_sub) {
9712 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009713 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009714 data_sub,
9715 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009716 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009717 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009718 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 else {
9720 /* We do not need to compare 0 and len(substring)-1 because
9721 the if statement above ensured already that they are equal
9722 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009723 for (i = 1; i < end_sub; ++i) {
9724 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9725 PyUnicode_READ(kind_sub, data_sub, i))
9726 return 0;
9727 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009728 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009729 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009730 }
9731
9732 return 0;
9733}
9734
Alexander Belopolsky40018472011-02-26 01:02:56 +00009735Py_ssize_t
9736PyUnicode_Tailmatch(PyObject *str,
9737 PyObject *substr,
9738 Py_ssize_t start,
9739 Py_ssize_t end,
9740 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009741{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009742 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009743 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009744
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009745 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009746}
9747
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009748static PyObject *
9749ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009750{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009751 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9752 char *resdata, *data = PyUnicode_DATA(self);
9753 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009754
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009755 res = PyUnicode_New(len, 127);
9756 if (res == NULL)
9757 return NULL;
9758 resdata = PyUnicode_DATA(res);
9759 if (lower)
9760 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009761 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009762 _Py_bytes_upper(resdata, data, len);
9763 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009764}
9765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009766static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009767handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009768{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009769 Py_ssize_t j;
9770 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009771 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009772 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009773
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009774 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9775
9776 where ! is a negation and \p{xxx} is a character with property xxx.
9777 */
9778 for (j = i - 1; j >= 0; j--) {
9779 c = PyUnicode_READ(kind, data, j);
9780 if (!_PyUnicode_IsCaseIgnorable(c))
9781 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009783 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9784 if (final_sigma) {
9785 for (j = i + 1; j < length; j++) {
9786 c = PyUnicode_READ(kind, data, j);
9787 if (!_PyUnicode_IsCaseIgnorable(c))
9788 break;
9789 }
9790 final_sigma = j == length || !_PyUnicode_IsCased(c);
9791 }
9792 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009793}
9794
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009795static int
9796lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9797 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009799 /* Obscure special case. */
9800 if (c == 0x3A3) {
9801 mapped[0] = handle_capital_sigma(kind, data, length, i);
9802 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009804 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009805}
9806
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009807static Py_ssize_t
9808do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009809{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009810 Py_ssize_t i, k = 0;
9811 int n_res, j;
9812 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009813
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009814 c = PyUnicode_READ(kind, data, 0);
Kingsley Mb015fc82019-04-12 16:35:39 +01009815 n_res = _PyUnicode_ToTitleFull(c, mapped);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009816 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009817 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009818 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009819 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009820 for (i = 1; i < length; i++) {
9821 c = PyUnicode_READ(kind, data, i);
9822 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9823 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009824 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009825 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009826 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009827 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009828 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009829}
9830
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009831static Py_ssize_t
9832do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9833 Py_ssize_t i, k = 0;
9834
9835 for (i = 0; i < length; i++) {
9836 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9837 int n_res, j;
9838 if (Py_UNICODE_ISUPPER(c)) {
9839 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9840 }
9841 else if (Py_UNICODE_ISLOWER(c)) {
9842 n_res = _PyUnicode_ToUpperFull(c, mapped);
9843 }
9844 else {
9845 n_res = 1;
9846 mapped[0] = c;
9847 }
9848 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009849 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009850 res[k++] = mapped[j];
9851 }
9852 }
9853 return k;
9854}
9855
9856static Py_ssize_t
9857do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9858 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009859{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009860 Py_ssize_t i, k = 0;
9861
9862 for (i = 0; i < length; i++) {
9863 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9864 int n_res, j;
9865 if (lower)
9866 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9867 else
9868 n_res = _PyUnicode_ToUpperFull(c, mapped);
9869 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009870 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009871 res[k++] = mapped[j];
9872 }
9873 }
9874 return k;
9875}
9876
9877static Py_ssize_t
9878do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9879{
9880 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9881}
9882
9883static Py_ssize_t
9884do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9885{
9886 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9887}
9888
Benjamin Petersone51757f2012-01-12 21:10:29 -05009889static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009890do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9891{
9892 Py_ssize_t i, k = 0;
9893
9894 for (i = 0; i < length; i++) {
9895 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9896 Py_UCS4 mapped[3];
9897 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9898 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009899 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009900 res[k++] = mapped[j];
9901 }
9902 }
9903 return k;
9904}
9905
9906static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009907do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9908{
9909 Py_ssize_t i, k = 0;
9910 int previous_is_cased;
9911
9912 previous_is_cased = 0;
9913 for (i = 0; i < length; i++) {
9914 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9915 Py_UCS4 mapped[3];
9916 int n_res, j;
9917
9918 if (previous_is_cased)
9919 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9920 else
9921 n_res = _PyUnicode_ToTitleFull(c, mapped);
9922
9923 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009924 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009925 res[k++] = mapped[j];
9926 }
9927
9928 previous_is_cased = _PyUnicode_IsCased(c);
9929 }
9930 return k;
9931}
9932
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009933static PyObject *
9934case_operation(PyObject *self,
9935 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9936{
9937 PyObject *res = NULL;
9938 Py_ssize_t length, newlength = 0;
9939 int kind, outkind;
9940 void *data, *outdata;
9941 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9942
Benjamin Petersoneea48462012-01-16 14:28:50 -05009943 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009944
9945 kind = PyUnicode_KIND(self);
9946 data = PyUnicode_DATA(self);
9947 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009948 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009949 PyErr_SetString(PyExc_OverflowError, "string is too long");
9950 return NULL;
9951 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009952 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009953 if (tmp == NULL)
9954 return PyErr_NoMemory();
9955 newlength = perform(kind, data, length, tmp, &maxchar);
9956 res = PyUnicode_New(newlength, maxchar);
9957 if (res == NULL)
9958 goto leave;
9959 tmpend = tmp + newlength;
9960 outdata = PyUnicode_DATA(res);
9961 outkind = PyUnicode_KIND(res);
9962 switch (outkind) {
9963 case PyUnicode_1BYTE_KIND:
9964 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9965 break;
9966 case PyUnicode_2BYTE_KIND:
9967 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9968 break;
9969 case PyUnicode_4BYTE_KIND:
9970 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9971 break;
9972 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009973 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009974 }
9975 leave:
9976 PyMem_FREE(tmp);
9977 return res;
9978}
9979
Tim Peters8ce9f162004-08-27 01:49:32 +00009980PyObject *
9981PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009982{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009983 PyObject *res;
9984 PyObject *fseq;
9985 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009986 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009987
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009988 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009989 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009990 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009991 }
9992
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009993 /* NOTE: the following code can't call back into Python code,
9994 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009995 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009996
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009997 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009998 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009999 res = _PyUnicode_JoinArray(separator, items, seqlen);
10000 Py_DECREF(fseq);
10001 return res;
10002}
10003
10004PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +020010005_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +030010006{
10007 PyObject *res = NULL; /* the result */
10008 PyObject *sep = NULL;
10009 Py_ssize_t seplen;
10010 PyObject *item;
10011 Py_ssize_t sz, i, res_offset;
10012 Py_UCS4 maxchar;
10013 Py_UCS4 item_maxchar;
10014 int use_memcpy;
10015 unsigned char *res_data = NULL, *sep_data = NULL;
10016 PyObject *last_obj;
10017 unsigned int kind = 0;
10018
Tim Peters05eba1f2004-08-27 21:32:02 +000010019 /* If empty sequence, return u"". */
10020 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010021 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +000010022 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010023
Tim Peters05eba1f2004-08-27 21:32:02 +000010024 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010025 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +020010026 if (seqlen == 1) {
10027 if (PyUnicode_CheckExact(items[0])) {
10028 res = items[0];
10029 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +020010030 return res;
10031 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010032 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +020010033 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +000010034 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010035 else {
Victor Stinneracf47b82011-10-06 12:32:37 +020010036 /* Set up sep and seplen */
10037 if (separator == NULL) {
10038 /* fall back to a blank space separator */
10039 sep = PyUnicode_FromOrdinal(' ');
10040 if (!sep)
10041 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +020010042 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +020010043 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +000010044 }
Victor Stinneracf47b82011-10-06 12:32:37 +020010045 else {
10046 if (!PyUnicode_Check(separator)) {
10047 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020010048 "separator: expected str instance,"
10049 " %.80s found",
10050 Py_TYPE(separator)->tp_name);
Victor Stinneracf47b82011-10-06 12:32:37 +020010051 goto onError;
10052 }
10053 if (PyUnicode_READY(separator))
10054 goto onError;
10055 sep = separator;
10056 seplen = PyUnicode_GET_LENGTH(separator);
10057 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10058 /* inc refcount to keep this code path symmetric with the
10059 above case of a blank separator */
10060 Py_INCREF(sep);
10061 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010062 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010063 }
10064
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010065 /* There are at least two things to join, or else we have a subclass
10066 * of str in the sequence.
10067 * Do a pre-pass to figure out the total amount of space we'll
10068 * need (sz), and see whether all argument are strings.
10069 */
10070 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010071#ifdef Py_DEBUG
10072 use_memcpy = 0;
10073#else
10074 use_memcpy = 1;
10075#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010076 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010077 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010078 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010079 if (!PyUnicode_Check(item)) {
10080 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020010081 "sequence item %zd: expected str instance,"
10082 " %.80s found",
10083 i, Py_TYPE(item)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000010084 goto onError;
10085 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 if (PyUnicode_READY(item) == -1)
10087 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010088 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010090 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010091 if (i != 0) {
10092 add_sz += seplen;
10093 }
10094 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010095 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010096 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010097 goto onError;
10098 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010099 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010100 if (use_memcpy && last_obj != NULL) {
10101 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10102 use_memcpy = 0;
10103 }
10104 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010105 }
Tim Petersced69f82003-09-16 20:30:58 +000010106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010108 if (res == NULL)
10109 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010110
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010111 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010112#ifdef Py_DEBUG
10113 use_memcpy = 0;
10114#else
10115 if (use_memcpy) {
10116 res_data = PyUnicode_1BYTE_DATA(res);
10117 kind = PyUnicode_KIND(res);
10118 if (seplen != 0)
10119 sep_data = PyUnicode_1BYTE_DATA(sep);
10120 }
10121#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010122 if (use_memcpy) {
10123 for (i = 0; i < seqlen; ++i) {
10124 Py_ssize_t itemlen;
10125 item = items[i];
10126
10127 /* Copy item, and maybe the separator. */
10128 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010129 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010130 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010131 kind * seplen);
10132 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010133 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010134
10135 itemlen = PyUnicode_GET_LENGTH(item);
10136 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010137 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010138 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010139 kind * itemlen);
10140 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010141 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010142 }
10143 assert(res_data == PyUnicode_1BYTE_DATA(res)
10144 + kind * PyUnicode_GET_LENGTH(res));
10145 }
10146 else {
10147 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10148 Py_ssize_t itemlen;
10149 item = items[i];
10150
10151 /* Copy item, and maybe the separator. */
10152 if (i && seplen != 0) {
10153 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10154 res_offset += seplen;
10155 }
10156
10157 itemlen = PyUnicode_GET_LENGTH(item);
10158 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010159 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010160 res_offset += itemlen;
10161 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010162 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010163 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010164 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010167 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169
Benjamin Peterson29060642009-01-31 22:14:21 +000010170 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010172 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173 return NULL;
10174}
10175
Victor Stinnerd3f08822012-05-29 12:57:52 +020010176void
10177_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10178 Py_UCS4 fill_char)
10179{
10180 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Victor Stinner163403a2018-11-27 12:41:17 +010010181 void *data = PyUnicode_DATA(unicode);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010182 assert(PyUnicode_IS_READY(unicode));
10183 assert(unicode_modifiable(unicode));
10184 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10185 assert(start >= 0);
10186 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner59423e32018-11-26 13:40:01 +010010187 unicode_fill(kind, data, fill_char, start, length);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010188}
10189
Victor Stinner3fe55312012-01-04 00:33:50 +010010190Py_ssize_t
10191PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10192 Py_UCS4 fill_char)
10193{
10194 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010195
10196 if (!PyUnicode_Check(unicode)) {
10197 PyErr_BadInternalCall();
10198 return -1;
10199 }
10200 if (PyUnicode_READY(unicode) == -1)
10201 return -1;
10202 if (unicode_check_modifiable(unicode))
10203 return -1;
10204
Victor Stinnerd3f08822012-05-29 12:57:52 +020010205 if (start < 0) {
10206 PyErr_SetString(PyExc_IndexError, "string index out of range");
10207 return -1;
10208 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010209 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10210 PyErr_SetString(PyExc_ValueError,
10211 "fill character is bigger than "
10212 "the string maximum character");
10213 return -1;
10214 }
10215
10216 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10217 length = Py_MIN(maxlen, length);
10218 if (length <= 0)
10219 return 0;
10220
Victor Stinnerd3f08822012-05-29 12:57:52 +020010221 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010222 return length;
10223}
10224
Victor Stinner9310abb2011-10-05 00:59:23 +020010225static PyObject *
10226pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010227 Py_ssize_t left,
10228 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010230{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 PyObject *u;
10232 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010233 int kind;
10234 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010235
10236 if (left < 0)
10237 left = 0;
10238 if (right < 0)
10239 right = 0;
10240
Victor Stinnerc4b49542011-12-11 22:44:26 +010010241 if (left == 0 && right == 0)
10242 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010243
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10245 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010246 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10247 return NULL;
10248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010250 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010252 if (!u)
10253 return NULL;
10254
10255 kind = PyUnicode_KIND(u);
10256 data = PyUnicode_DATA(u);
10257 if (left)
Victor Stinner59423e32018-11-26 13:40:01 +010010258 unicode_fill(kind, data, fill, 0, left);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010259 if (right)
Victor Stinner59423e32018-11-26 13:40:01 +010010260 unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010261 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010262 assert(_PyUnicode_CheckConsistency(u, 1));
10263 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010264}
10265
Alexander Belopolsky40018472011-02-26 01:02:56 +000010266PyObject *
10267PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010268{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010269 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010270
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010271 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010272 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010273
Benjamin Petersonead6b532011-12-20 17:23:42 -060010274 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010276 if (PyUnicode_IS_ASCII(string))
10277 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010278 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010279 PyUnicode_GET_LENGTH(string), keepends);
10280 else
10281 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010282 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010283 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 break;
10285 case PyUnicode_2BYTE_KIND:
10286 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010287 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 PyUnicode_GET_LENGTH(string), keepends);
10289 break;
10290 case PyUnicode_4BYTE_KIND:
10291 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010292 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 PyUnicode_GET_LENGTH(string), keepends);
10294 break;
10295 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010296 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010298 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299}
10300
Alexander Belopolsky40018472011-02-26 01:02:56 +000010301static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010302split(PyObject *self,
10303 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010304 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010305{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010306 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 void *buf1, *buf2;
10308 Py_ssize_t len1, len2;
10309 PyObject* out;
10310
Guido van Rossumd57fd912000-03-10 22:53:23 +000010311 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010312 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 if (PyUnicode_READY(self) == -1)
10315 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010318 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010320 if (PyUnicode_IS_ASCII(self))
10321 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010322 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010323 PyUnicode_GET_LENGTH(self), maxcount
10324 );
10325 else
10326 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010327 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010328 PyUnicode_GET_LENGTH(self), maxcount
10329 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 case PyUnicode_2BYTE_KIND:
10331 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010332 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 PyUnicode_GET_LENGTH(self), maxcount
10334 );
10335 case PyUnicode_4BYTE_KIND:
10336 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010337 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 PyUnicode_GET_LENGTH(self), maxcount
10339 );
10340 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010341 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 }
10343
10344 if (PyUnicode_READY(substring) == -1)
10345 return NULL;
10346
10347 kind1 = PyUnicode_KIND(self);
10348 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 len1 = PyUnicode_GET_LENGTH(self);
10350 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010351 if (kind1 < kind2 || len1 < len2) {
10352 out = PyList_New(1);
10353 if (out == NULL)
10354 return NULL;
10355 Py_INCREF(self);
10356 PyList_SET_ITEM(out, 0, self);
10357 return out;
10358 }
10359 buf1 = PyUnicode_DATA(self);
10360 buf2 = PyUnicode_DATA(substring);
10361 if (kind2 != kind1) {
10362 buf2 = _PyUnicode_AsKind(substring, kind1);
10363 if (!buf2)
10364 return NULL;
10365 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010366
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010367 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010369 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10370 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010371 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010372 else
10373 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010374 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 break;
10376 case PyUnicode_2BYTE_KIND:
10377 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010378 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 break;
10380 case PyUnicode_4BYTE_KIND:
10381 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010382 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 break;
10384 default:
10385 out = NULL;
10386 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010387 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 PyMem_Free(buf2);
10389 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010390}
10391
Alexander Belopolsky40018472011-02-26 01:02:56 +000010392static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010393rsplit(PyObject *self,
10394 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010395 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010396{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010397 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 void *buf1, *buf2;
10399 Py_ssize_t len1, len2;
10400 PyObject* out;
10401
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010402 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010403 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 if (PyUnicode_READY(self) == -1)
10406 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010409 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010411 if (PyUnicode_IS_ASCII(self))
10412 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010413 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010414 PyUnicode_GET_LENGTH(self), maxcount
10415 );
10416 else
10417 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010418 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010419 PyUnicode_GET_LENGTH(self), maxcount
10420 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 case PyUnicode_2BYTE_KIND:
10422 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010423 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 PyUnicode_GET_LENGTH(self), maxcount
10425 );
10426 case PyUnicode_4BYTE_KIND:
10427 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010428 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429 PyUnicode_GET_LENGTH(self), maxcount
10430 );
10431 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010432 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 }
10434
10435 if (PyUnicode_READY(substring) == -1)
10436 return NULL;
10437
10438 kind1 = PyUnicode_KIND(self);
10439 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010440 len1 = PyUnicode_GET_LENGTH(self);
10441 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010442 if (kind1 < kind2 || len1 < len2) {
10443 out = PyList_New(1);
10444 if (out == NULL)
10445 return NULL;
10446 Py_INCREF(self);
10447 PyList_SET_ITEM(out, 0, self);
10448 return out;
10449 }
10450 buf1 = PyUnicode_DATA(self);
10451 buf2 = PyUnicode_DATA(substring);
10452 if (kind2 != kind1) {
10453 buf2 = _PyUnicode_AsKind(substring, kind1);
10454 if (!buf2)
10455 return NULL;
10456 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010458 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010460 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10461 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010462 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010463 else
10464 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010465 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 break;
10467 case PyUnicode_2BYTE_KIND:
10468 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010469 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 break;
10471 case PyUnicode_4BYTE_KIND:
10472 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010473 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 break;
10475 default:
10476 out = NULL;
10477 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010478 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 PyMem_Free(buf2);
10480 return out;
10481}
10482
10483static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010484anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10485 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010487 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010489 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10490 return asciilib_find(buf1, len1, buf2, len2, offset);
10491 else
10492 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010493 case PyUnicode_2BYTE_KIND:
10494 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10495 case PyUnicode_4BYTE_KIND:
10496 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10497 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010498 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499}
10500
10501static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010502anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10503 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010504{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010505 switch (kind) {
10506 case PyUnicode_1BYTE_KIND:
10507 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10508 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10509 else
10510 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10511 case PyUnicode_2BYTE_KIND:
10512 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10513 case PyUnicode_4BYTE_KIND:
10514 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10515 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010516 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010517}
10518
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010519static void
10520replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10521 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10522{
10523 int kind = PyUnicode_KIND(u);
10524 void *data = PyUnicode_DATA(u);
10525 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10526 if (kind == PyUnicode_1BYTE_KIND) {
10527 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10528 (Py_UCS1 *)data + len,
10529 u1, u2, maxcount);
10530 }
10531 else if (kind == PyUnicode_2BYTE_KIND) {
10532 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10533 (Py_UCS2 *)data + len,
10534 u1, u2, maxcount);
10535 }
10536 else {
10537 assert(kind == PyUnicode_4BYTE_KIND);
10538 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10539 (Py_UCS4 *)data + len,
10540 u1, u2, maxcount);
10541 }
10542}
10543
Alexander Belopolsky40018472011-02-26 01:02:56 +000010544static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010545replace(PyObject *self, PyObject *str1,
10546 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010547{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010548 PyObject *u;
10549 char *sbuf = PyUnicode_DATA(self);
10550 char *buf1 = PyUnicode_DATA(str1);
10551 char *buf2 = PyUnicode_DATA(str2);
10552 int srelease = 0, release1 = 0, release2 = 0;
10553 int skind = PyUnicode_KIND(self);
10554 int kind1 = PyUnicode_KIND(str1);
10555 int kind2 = PyUnicode_KIND(str2);
10556 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10557 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10558 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010559 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010560 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010561
10562 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010563 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010565 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010566
Victor Stinner59de0ee2011-10-07 10:01:28 +020010567 if (str1 == str2)
10568 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569
Victor Stinner49a0a212011-10-12 23:46:10 +020010570 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010571 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10572 if (maxchar < maxchar_str1)
10573 /* substring too wide to be present */
10574 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010575 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10576 /* Replacing str1 with str2 may cause a maxchar reduction in the
10577 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010578 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010579 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010582 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010584 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010586 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010587 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010588 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010589
Victor Stinner69ed0f42013-04-09 21:48:24 +020010590 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010591 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010592 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010594 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010596 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010598
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010599 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10600 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010601 }
10602 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 int rkind = skind;
10604 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010605 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 if (kind1 < rkind) {
10608 /* widen substring */
10609 buf1 = _PyUnicode_AsKind(str1, rkind);
10610 if (!buf1) goto error;
10611 release1 = 1;
10612 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010613 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010614 if (i < 0)
10615 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 if (rkind > kind2) {
10617 /* widen replacement */
10618 buf2 = _PyUnicode_AsKind(str2, rkind);
10619 if (!buf2) goto error;
10620 release2 = 1;
10621 }
10622 else if (rkind < kind2) {
10623 /* widen self and buf1 */
10624 rkind = kind2;
10625 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010626 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010627 sbuf = _PyUnicode_AsKind(self, rkind);
10628 if (!sbuf) goto error;
10629 srelease = 1;
10630 buf1 = _PyUnicode_AsKind(str1, rkind);
10631 if (!buf1) goto error;
10632 release1 = 1;
10633 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010634 u = PyUnicode_New(slen, maxchar);
10635 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010637 assert(PyUnicode_KIND(u) == rkind);
10638 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010639
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010640 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010641 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010642 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010643 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010644 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010646
10647 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010648 i = 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 (i == -1)
10652 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010653 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010655 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010657 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010658 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010659 }
10660 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010662 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 int rkind = skind;
10664 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010665
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010667 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010668 buf1 = _PyUnicode_AsKind(str1, rkind);
10669 if (!buf1) goto error;
10670 release1 = 1;
10671 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010672 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010673 if (n == 0)
10674 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010676 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010677 buf2 = _PyUnicode_AsKind(str2, rkind);
10678 if (!buf2) goto error;
10679 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010682 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 rkind = kind2;
10684 sbuf = _PyUnicode_AsKind(self, rkind);
10685 if (!sbuf) goto error;
10686 srelease = 1;
10687 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010688 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010689 buf1 = _PyUnicode_AsKind(str1, rkind);
10690 if (!buf1) goto error;
10691 release1 = 1;
10692 }
10693 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10694 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010695 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010696 PyErr_SetString(PyExc_OverflowError,
10697 "replace string is too long");
10698 goto error;
10699 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010700 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010701 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010702 _Py_INCREF_UNICODE_EMPTY();
10703 if (!unicode_empty)
10704 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010705 u = unicode_empty;
10706 goto done;
10707 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010708 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709 PyErr_SetString(PyExc_OverflowError,
10710 "replace string is too long");
10711 goto error;
10712 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010713 u = PyUnicode_New(new_size, maxchar);
10714 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010715 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010716 assert(PyUnicode_KIND(u) == rkind);
10717 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010718 ires = i = 0;
10719 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010720 while (n-- > 0) {
10721 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010722 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010723 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010724 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010725 if (j == -1)
10726 break;
10727 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010728 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010729 memcpy(res + rkind * ires,
10730 sbuf + rkind * i,
10731 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010733 }
10734 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010736 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010737 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010738 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010739 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010741 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010742 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010743 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010744 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010745 memcpy(res + rkind * ires,
10746 sbuf + rkind * i,
10747 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010748 }
10749 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010750 /* interleave */
10751 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010752 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010753 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010754 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010755 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010756 if (--n <= 0)
10757 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010758 memcpy(res + rkind * ires,
10759 sbuf + rkind * i,
10760 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010761 ires++;
10762 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010763 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010764 memcpy(res + rkind * ires,
10765 sbuf + rkind * i,
10766 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010767 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010768 }
10769
10770 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010771 unicode_adjust_maxchar(&u);
10772 if (u == NULL)
10773 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010775
10776 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010777 if (srelease)
10778 PyMem_FREE(sbuf);
10779 if (release1)
10780 PyMem_FREE(buf1);
10781 if (release2)
10782 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010783 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010785
Benjamin Peterson29060642009-01-31 22:14:21 +000010786 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010787 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 if (srelease)
10789 PyMem_FREE(sbuf);
10790 if (release1)
10791 PyMem_FREE(buf1);
10792 if (release2)
10793 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010794 return unicode_result_unchanged(self);
10795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010796 error:
10797 if (srelease && sbuf)
10798 PyMem_FREE(sbuf);
10799 if (release1 && buf1)
10800 PyMem_FREE(buf1);
10801 if (release2 && buf2)
10802 PyMem_FREE(buf2);
10803 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804}
10805
10806/* --- Unicode Object Methods --------------------------------------------- */
10807
INADA Naoki3ae20562017-01-16 20:41:20 +090010808/*[clinic input]
10809str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810
INADA Naoki3ae20562017-01-16 20:41:20 +090010811Return a version of the string where each word is titlecased.
10812
10813More specifically, words start with uppercased characters and all remaining
10814cased characters have lower case.
10815[clinic start generated code]*/
10816
10817static PyObject *
10818unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010819/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010820{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010821 if (PyUnicode_READY(self) == -1)
10822 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010823 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010824}
10825
INADA Naoki3ae20562017-01-16 20:41:20 +090010826/*[clinic input]
10827str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010828
INADA Naoki3ae20562017-01-16 20:41:20 +090010829Return a capitalized version of the string.
10830
10831More specifically, make the first character have upper case and the rest lower
10832case.
10833[clinic start generated code]*/
10834
10835static PyObject *
10836unicode_capitalize_impl(PyObject *self)
10837/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010839 if (PyUnicode_READY(self) == -1)
10840 return NULL;
10841 if (PyUnicode_GET_LENGTH(self) == 0)
10842 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010843 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010844}
10845
INADA Naoki3ae20562017-01-16 20:41:20 +090010846/*[clinic input]
10847str.casefold as unicode_casefold
10848
10849Return a version of the string suitable for caseless comparisons.
10850[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010851
10852static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010853unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010854/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010855{
10856 if (PyUnicode_READY(self) == -1)
10857 return NULL;
10858 if (PyUnicode_IS_ASCII(self))
10859 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010860 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010861}
10862
10863
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010864/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010865
10866static int
10867convert_uc(PyObject *obj, void *addr)
10868{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010869 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010870
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010871 if (!PyUnicode_Check(obj)) {
10872 PyErr_Format(PyExc_TypeError,
10873 "The fill character must be a unicode character, "
Victor Stinner998b8062018-09-12 00:23:25 +020010874 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010875 return 0;
10876 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010877 if (PyUnicode_READY(obj) < 0)
10878 return 0;
10879 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010880 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010881 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010882 return 0;
10883 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010884 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010885 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010886}
10887
INADA Naoki3ae20562017-01-16 20:41:20 +090010888/*[clinic input]
10889str.center as unicode_center
10890
10891 width: Py_ssize_t
10892 fillchar: Py_UCS4 = ' '
10893 /
10894
10895Return a centered string of length width.
10896
10897Padding is done using the specified fill character (default is a space).
10898[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899
10900static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010901unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10902/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010903{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010904 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010905
Benjamin Petersonbac79492012-01-14 13:34:47 -050010906 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907 return NULL;
10908
Victor Stinnerc4b49542011-12-11 22:44:26 +010010909 if (PyUnicode_GET_LENGTH(self) >= width)
10910 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010911
Victor Stinnerc4b49542011-12-11 22:44:26 +010010912 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913 left = marg / 2 + (marg & width & 1);
10914
Victor Stinner9310abb2011-10-05 00:59:23 +020010915 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916}
10917
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918/* This function assumes that str1 and str2 are readied by the caller. */
10919
Marc-André Lemburge5034372000-08-08 08:04:29 +000010920static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010921unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010922{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010923#define COMPARE(TYPE1, TYPE2) \
10924 do { \
10925 TYPE1* p1 = (TYPE1 *)data1; \
10926 TYPE2* p2 = (TYPE2 *)data2; \
10927 TYPE1* end = p1 + len; \
10928 Py_UCS4 c1, c2; \
10929 for (; p1 != end; p1++, p2++) { \
10930 c1 = *p1; \
10931 c2 = *p2; \
10932 if (c1 != c2) \
10933 return (c1 < c2) ? -1 : 1; \
10934 } \
10935 } \
10936 while (0)
10937
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938 int kind1, kind2;
10939 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010940 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010942 kind1 = PyUnicode_KIND(str1);
10943 kind2 = PyUnicode_KIND(str2);
10944 data1 = PyUnicode_DATA(str1);
10945 data2 = PyUnicode_DATA(str2);
10946 len1 = PyUnicode_GET_LENGTH(str1);
10947 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010948 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010949
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010950 switch(kind1) {
10951 case PyUnicode_1BYTE_KIND:
10952 {
10953 switch(kind2) {
10954 case PyUnicode_1BYTE_KIND:
10955 {
10956 int cmp = memcmp(data1, data2, len);
10957 /* normalize result of memcmp() into the range [-1; 1] */
10958 if (cmp < 0)
10959 return -1;
10960 if (cmp > 0)
10961 return 1;
10962 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010963 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010964 case PyUnicode_2BYTE_KIND:
10965 COMPARE(Py_UCS1, Py_UCS2);
10966 break;
10967 case PyUnicode_4BYTE_KIND:
10968 COMPARE(Py_UCS1, Py_UCS4);
10969 break;
10970 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010971 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010972 }
10973 break;
10974 }
10975 case PyUnicode_2BYTE_KIND:
10976 {
10977 switch(kind2) {
10978 case PyUnicode_1BYTE_KIND:
10979 COMPARE(Py_UCS2, Py_UCS1);
10980 break;
10981 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010982 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010983 COMPARE(Py_UCS2, Py_UCS2);
10984 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010985 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010986 case PyUnicode_4BYTE_KIND:
10987 COMPARE(Py_UCS2, Py_UCS4);
10988 break;
10989 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010990 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010991 }
10992 break;
10993 }
10994 case PyUnicode_4BYTE_KIND:
10995 {
10996 switch(kind2) {
10997 case PyUnicode_1BYTE_KIND:
10998 COMPARE(Py_UCS4, Py_UCS1);
10999 break;
11000 case PyUnicode_2BYTE_KIND:
11001 COMPARE(Py_UCS4, Py_UCS2);
11002 break;
11003 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020011004 {
11005#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11006 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11007 /* normalize result of wmemcmp() into the range [-1; 1] */
11008 if (cmp < 0)
11009 return -1;
11010 if (cmp > 0)
11011 return 1;
11012#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011013 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020011014#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011015 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020011016 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011017 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011018 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011019 }
11020 break;
11021 }
11022 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011023 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000011024 }
11025
Victor Stinner770e19e2012-10-04 22:59:45 +020011026 if (len1 == len2)
11027 return 0;
11028 if (len1 < len2)
11029 return -1;
11030 else
11031 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011032
11033#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000011034}
11035
Benjamin Peterson621b4302016-09-09 13:54:34 -070011036static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020011037unicode_compare_eq(PyObject *str1, PyObject *str2)
11038{
11039 int kind;
11040 void *data1, *data2;
11041 Py_ssize_t len;
11042 int cmp;
11043
Victor Stinnere5567ad2012-10-23 02:48:49 +020011044 len = PyUnicode_GET_LENGTH(str1);
11045 if (PyUnicode_GET_LENGTH(str2) != len)
11046 return 0;
11047 kind = PyUnicode_KIND(str1);
11048 if (PyUnicode_KIND(str2) != kind)
11049 return 0;
11050 data1 = PyUnicode_DATA(str1);
11051 data2 = PyUnicode_DATA(str2);
11052
11053 cmp = memcmp(data1, data2, len * kind);
11054 return (cmp == 0);
11055}
11056
11057
Alexander Belopolsky40018472011-02-26 01:02:56 +000011058int
11059PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011061 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11062 if (PyUnicode_READY(left) == -1 ||
11063 PyUnicode_READY(right) == -1)
11064 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011065
11066 /* a string is equal to itself */
11067 if (left == right)
11068 return 0;
11069
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011070 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011071 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011072 PyErr_Format(PyExc_TypeError,
11073 "Can't compare %.100s and %.100s",
11074 left->ob_type->tp_name,
11075 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011076 return -1;
11077}
11078
Martin v. Löwis5b222132007-06-10 09:51:05 +000011079int
11080PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11081{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011082 Py_ssize_t i;
11083 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011084 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011085 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011086
Victor Stinner910337b2011-10-03 03:20:16 +020011087 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011088 if (!PyUnicode_IS_READY(uni)) {
11089 const wchar_t *ws = _PyUnicode_WSTR(uni);
11090 /* Compare Unicode string and source character set string */
11091 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11092 if (chr != ustr[i])
11093 return (chr < ustr[i]) ? -1 : 1;
11094 }
11095 /* This check keeps Python strings that end in '\0' from comparing equal
11096 to C strings identical up to that point. */
11097 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11098 return 1; /* uni is longer */
11099 if (ustr[i])
11100 return -1; /* str is longer */
11101 return 0;
11102 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011103 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011104 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011105 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011106 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011107 size_t len, len2 = strlen(str);
11108 int cmp;
11109
11110 len = Py_MIN(len1, len2);
11111 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011112 if (cmp != 0) {
11113 if (cmp < 0)
11114 return -1;
11115 else
11116 return 1;
11117 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011118 if (len1 > len2)
11119 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011120 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011121 return -1; /* str is longer */
11122 return 0;
11123 }
11124 else {
11125 void *data = PyUnicode_DATA(uni);
11126 /* Compare Unicode string and source character set string */
11127 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011128 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011129 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11130 /* This check keeps Python strings that end in '\0' from comparing equal
11131 to C strings identical up to that point. */
11132 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11133 return 1; /* uni is longer */
11134 if (str[i])
11135 return -1; /* str is longer */
11136 return 0;
11137 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011138}
11139
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011140static int
11141non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11142{
11143 size_t i, len;
11144 const wchar_t *p;
11145 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11146 if (strlen(str) != len)
11147 return 0;
11148 p = _PyUnicode_WSTR(unicode);
11149 assert(p);
11150 for (i = 0; i < len; i++) {
11151 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011152 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011153 return 0;
11154 }
11155 return 1;
11156}
11157
11158int
11159_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11160{
11161 size_t len;
11162 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011163 assert(str);
11164#ifndef NDEBUG
11165 for (const char *p = str; *p; p++) {
11166 assert((unsigned char)*p < 128);
11167 }
11168#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011169 if (PyUnicode_READY(unicode) == -1) {
11170 /* Memory error or bad data */
11171 PyErr_Clear();
11172 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11173 }
11174 if (!PyUnicode_IS_ASCII(unicode))
11175 return 0;
11176 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11177 return strlen(str) == len &&
11178 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11179}
11180
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011181int
11182_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11183{
11184 PyObject *right_uni;
11185 Py_hash_t hash;
11186
11187 assert(_PyUnicode_CHECK(left));
11188 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011189#ifndef NDEBUG
11190 for (const char *p = right->string; *p; p++) {
11191 assert((unsigned char)*p < 128);
11192 }
11193#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011194
11195 if (PyUnicode_READY(left) == -1) {
11196 /* memory error or bad data */
11197 PyErr_Clear();
11198 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11199 }
11200
11201 if (!PyUnicode_IS_ASCII(left))
11202 return 0;
11203
11204 right_uni = _PyUnicode_FromId(right); /* borrowed */
11205 if (right_uni == NULL) {
11206 /* memory error or bad data */
11207 PyErr_Clear();
11208 return _PyUnicode_EqualToASCIIString(left, right->string);
11209 }
11210
11211 if (left == right_uni)
11212 return 1;
11213
11214 if (PyUnicode_CHECK_INTERNED(left))
11215 return 0;
11216
INADA Naoki7cc95f52018-01-28 02:07:09 +090011217 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011218 hash = _PyUnicode_HASH(left);
11219 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11220 return 0;
11221
11222 return unicode_compare_eq(left, right_uni);
11223}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011224
Alexander Belopolsky40018472011-02-26 01:02:56 +000011225PyObject *
11226PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011227{
11228 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011229
Victor Stinnere5567ad2012-10-23 02:48:49 +020011230 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11231 Py_RETURN_NOTIMPLEMENTED;
11232
11233 if (PyUnicode_READY(left) == -1 ||
11234 PyUnicode_READY(right) == -1)
11235 return NULL;
11236
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011237 if (left == right) {
11238 switch (op) {
11239 case Py_EQ:
11240 case Py_LE:
11241 case Py_GE:
11242 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011243 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011244 case Py_NE:
11245 case Py_LT:
11246 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011247 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011248 default:
11249 PyErr_BadArgument();
11250 return NULL;
11251 }
11252 }
11253 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011254 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011255 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011256 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011257 }
11258 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011259 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011260 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011261 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011262}
11263
Alexander Belopolsky40018472011-02-26 01:02:56 +000011264int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011265_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11266{
11267 return unicode_eq(aa, bb);
11268}
11269
11270int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011271PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011272{
Victor Stinner77282cb2013-04-14 19:22:47 +020011273 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 void *buf1, *buf2;
11275 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011276 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011277
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011278 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011279 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020011280 "'in <string>' requires string as left operand, not %.100s",
11281 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011282 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011283 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011284 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011285 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011286 if (ensure_unicode(str) < 0)
11287 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011288
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011290 kind2 = PyUnicode_KIND(substr);
11291 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011292 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011293 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011294 len2 = PyUnicode_GET_LENGTH(substr);
11295 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011296 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011297 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011298 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011299 if (len2 == 1) {
11300 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11301 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011302 return result;
11303 }
11304 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011305 buf2 = _PyUnicode_AsKind(substr, kind1);
11306 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011307 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309
Victor Stinner77282cb2013-04-14 19:22:47 +020011310 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011311 case PyUnicode_1BYTE_KIND:
11312 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11313 break;
11314 case PyUnicode_2BYTE_KIND:
11315 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11316 break;
11317 case PyUnicode_4BYTE_KIND:
11318 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11319 break;
11320 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011321 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011322 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011323
Victor Stinner77282cb2013-04-14 19:22:47 +020011324 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 PyMem_Free(buf2);
11326
Guido van Rossum403d68b2000-03-13 15:55:09 +000011327 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011328}
11329
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330/* Concat to string or Unicode object giving a new Unicode object. */
11331
Alexander Belopolsky40018472011-02-26 01:02:56 +000011332PyObject *
11333PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011335 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011336 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011337 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011339 if (ensure_unicode(left) < 0)
11340 return NULL;
11341
11342 if (!PyUnicode_Check(right)) {
11343 PyErr_Format(PyExc_TypeError,
11344 "can only concatenate str (not \"%.200s\") to str",
11345 right->ob_type->tp_name);
11346 return NULL;
11347 }
11348 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011349 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350
11351 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011352 if (left == unicode_empty)
11353 return PyUnicode_FromObject(right);
11354 if (right == unicode_empty)
11355 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011357 left_len = PyUnicode_GET_LENGTH(left);
11358 right_len = PyUnicode_GET_LENGTH(right);
11359 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011360 PyErr_SetString(PyExc_OverflowError,
11361 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011362 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011363 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011364 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011365
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011366 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11367 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011368 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011369
Guido van Rossumd57fd912000-03-10 22:53:23 +000011370 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011371 result = PyUnicode_New(new_len, maxchar);
11372 if (result == NULL)
11373 return NULL;
11374 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11375 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11376 assert(_PyUnicode_CheckConsistency(result, 1));
11377 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378}
11379
Walter Dörwald1ab83302007-05-18 17:15:44 +000011380void
Victor Stinner23e56682011-10-03 03:54:37 +020011381PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011382{
Victor Stinner23e56682011-10-03 03:54:37 +020011383 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011384 Py_UCS4 maxchar, maxchar2;
11385 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011386
11387 if (p_left == NULL) {
11388 if (!PyErr_Occurred())
11389 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011390 return;
11391 }
Victor Stinner23e56682011-10-03 03:54:37 +020011392 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011393 if (right == NULL || left == NULL
11394 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011395 if (!PyErr_Occurred())
11396 PyErr_BadInternalCall();
11397 goto error;
11398 }
11399
Benjamin Petersonbac79492012-01-14 13:34:47 -050011400 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011401 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011402 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011403 goto error;
11404
Victor Stinner488fa492011-12-12 00:01:39 +010011405 /* Shortcuts */
11406 if (left == unicode_empty) {
11407 Py_DECREF(left);
11408 Py_INCREF(right);
11409 *p_left = right;
11410 return;
11411 }
11412 if (right == unicode_empty)
11413 return;
11414
11415 left_len = PyUnicode_GET_LENGTH(left);
11416 right_len = PyUnicode_GET_LENGTH(right);
11417 if (left_len > PY_SSIZE_T_MAX - right_len) {
11418 PyErr_SetString(PyExc_OverflowError,
11419 "strings are too large to concat");
11420 goto error;
11421 }
11422 new_len = left_len + right_len;
11423
11424 if (unicode_modifiable(left)
11425 && PyUnicode_CheckExact(right)
11426 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011427 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11428 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011429 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011430 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011431 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11432 {
11433 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011434 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011435 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011436
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011437 /* copy 'right' into the newly allocated area of 'left' */
11438 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011439 }
Victor Stinner488fa492011-12-12 00:01:39 +010011440 else {
11441 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11442 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011443 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011444
Victor Stinner488fa492011-12-12 00:01:39 +010011445 /* Concat the two Unicode strings */
11446 res = PyUnicode_New(new_len, maxchar);
11447 if (res == NULL)
11448 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011449 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11450 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011451 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011452 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011453 }
11454 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011455 return;
11456
11457error:
Victor Stinner488fa492011-12-12 00:01:39 +010011458 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011459}
11460
11461void
11462PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11463{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011464 PyUnicode_Append(pleft, right);
11465 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011466}
11467
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011468/*
11469Wraps stringlib_parse_args_finds() and additionally ensures that the
11470first argument is a unicode object.
11471*/
11472
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011473static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011474parse_args_finds_unicode(const char * function_name, PyObject *args,
11475 PyObject **substring,
11476 Py_ssize_t *start, Py_ssize_t *end)
11477{
11478 if(stringlib_parse_args_finds(function_name, args, substring,
11479 start, end)) {
11480 if (ensure_unicode(*substring) < 0)
11481 return 0;
11482 return 1;
11483 }
11484 return 0;
11485}
11486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011487PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011490Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011491string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011492interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493
11494static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011495unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011497 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011498 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011499 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011501 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011502 void *buf1, *buf2;
11503 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011505 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011507
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011508 kind1 = PyUnicode_KIND(self);
11509 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011510 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011511 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011513 len1 = PyUnicode_GET_LENGTH(self);
11514 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011516 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011517 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011518
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011519 buf1 = PyUnicode_DATA(self);
11520 buf2 = PyUnicode_DATA(substring);
11521 if (kind2 != kind1) {
11522 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011523 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011524 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011525 }
11526 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 case PyUnicode_1BYTE_KIND:
11528 iresult = ucs1lib_count(
11529 ((Py_UCS1*)buf1) + start, end - start,
11530 buf2, len2, PY_SSIZE_T_MAX
11531 );
11532 break;
11533 case PyUnicode_2BYTE_KIND:
11534 iresult = ucs2lib_count(
11535 ((Py_UCS2*)buf1) + start, end - start,
11536 buf2, len2, PY_SSIZE_T_MAX
11537 );
11538 break;
11539 case PyUnicode_4BYTE_KIND:
11540 iresult = ucs4lib_count(
11541 ((Py_UCS4*)buf1) + start, end - start,
11542 buf2, len2, PY_SSIZE_T_MAX
11543 );
11544 break;
11545 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011546 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 }
11548
11549 result = PyLong_FromSsize_t(iresult);
11550
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011551 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554 return result;
11555}
11556
INADA Naoki3ae20562017-01-16 20:41:20 +090011557/*[clinic input]
11558str.encode as unicode_encode
11559
11560 encoding: str(c_default="NULL") = 'utf-8'
11561 The encoding in which to encode the string.
11562 errors: str(c_default="NULL") = 'strict'
11563 The error handling scheme to use for encoding errors.
11564 The default is 'strict' meaning that encoding errors raise a
11565 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11566 'xmlcharrefreplace' as well as any other name registered with
11567 codecs.register_error that can handle UnicodeEncodeErrors.
11568
11569Encode the string using the codec registered for encoding.
11570[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571
11572static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011573unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011574/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011576 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011577}
11578
INADA Naoki3ae20562017-01-16 20:41:20 +090011579/*[clinic input]
11580str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581
INADA Naoki3ae20562017-01-16 20:41:20 +090011582 tabsize: int = 8
11583
11584Return a copy where all tab characters are expanded using spaces.
11585
11586If tabsize is not given, a tab size of 8 characters is assumed.
11587[clinic start generated code]*/
11588
11589static PyObject *
11590unicode_expandtabs_impl(PyObject *self, int tabsize)
11591/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011593 Py_ssize_t i, j, line_pos, src_len, incr;
11594 Py_UCS4 ch;
11595 PyObject *u;
11596 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011597 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011598 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599
Antoine Pitrou22425222011-10-04 19:10:51 +020011600 if (PyUnicode_READY(self) == -1)
11601 return NULL;
11602
Thomas Wouters7e474022000-07-16 12:04:32 +000011603 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011604 src_len = PyUnicode_GET_LENGTH(self);
11605 i = j = line_pos = 0;
11606 kind = PyUnicode_KIND(self);
11607 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011608 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011609 for (; i < src_len; i++) {
11610 ch = PyUnicode_READ(kind, src_data, i);
11611 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011612 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011613 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011614 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011615 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011616 goto overflow;
11617 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011619 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011620 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011622 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011623 goto overflow;
11624 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011626 if (ch == '\n' || ch == '\r')
11627 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011629 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011630 if (!found)
11631 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011632
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011634 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011635 if (!u)
11636 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011637 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011638
Antoine Pitroue71d5742011-10-04 15:55:09 +020011639 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640
Antoine Pitroue71d5742011-10-04 15:55:09 +020011641 for (; i < src_len; i++) {
11642 ch = PyUnicode_READ(kind, src_data, i);
11643 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011644 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011645 incr = tabsize - (line_pos % tabsize);
11646 line_pos += incr;
Victor Stinner59423e32018-11-26 13:40:01 +010011647 unicode_fill(kind, dest_data, ' ', j, incr);
Victor Stinnerda79e632012-02-22 13:37:04 +010011648 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011650 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011651 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011652 line_pos++;
11653 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011654 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011655 if (ch == '\n' || ch == '\r')
11656 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011658 }
11659 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011660 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011661
Antoine Pitroue71d5742011-10-04 15:55:09 +020011662 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011663 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11664 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665}
11666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011667PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011668 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011669\n\
11670Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011671such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672arguments start and end are interpreted as in slice notation.\n\
11673\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011674Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675
11676static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011677unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011679 /* initialize variables to prevent gcc warning */
11680 PyObject *substring = NULL;
11681 Py_ssize_t start = 0;
11682 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011683 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011685 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011686 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011688 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011691 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 if (result == -2)
11694 return NULL;
11695
Christian Heimes217cfd12007-12-02 14:31:20 +000011696 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697}
11698
11699static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011700unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011702 void *data;
11703 enum PyUnicode_Kind kind;
11704 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011705
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011706 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011707 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011709 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011710 if (PyUnicode_READY(self) == -1) {
11711 return NULL;
11712 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011713 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11714 PyErr_SetString(PyExc_IndexError, "string index out of range");
11715 return NULL;
11716 }
11717 kind = PyUnicode_KIND(self);
11718 data = PyUnicode_DATA(self);
11719 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011720 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721}
11722
Guido van Rossumc2504932007-09-18 19:42:40 +000011723/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011724 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011725static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011726unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727{
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011728 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011729
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011730#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011731 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011732#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011733 if (_PyUnicode_HASH(self) != -1)
11734 return _PyUnicode_HASH(self);
11735 if (PyUnicode_READY(self) == -1)
11736 return -1;
animalizea1d14252019-01-02 20:16:06 +080011737
Christian Heimes985ecdc2013-11-20 11:46:18 +010011738 x = _Py_HashBytes(PyUnicode_DATA(self),
11739 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011740 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011741 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742}
11743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011744PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011745 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746\n\
oldkaa0735f2018-02-02 16:52:55 +080011747Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011748such that sub is contained within S[start:end]. Optional\n\
11749arguments start and end are interpreted as in slice notation.\n\
11750\n\
11751Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752
11753static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011754unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011756 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011757 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011758 PyObject *substring = NULL;
11759 Py_ssize_t start = 0;
11760 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011762 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011765 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011768 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 if (result == -2)
11771 return NULL;
11772
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773 if (result < 0) {
11774 PyErr_SetString(PyExc_ValueError, "substring not found");
11775 return NULL;
11776 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011777
Christian Heimes217cfd12007-12-02 14:31:20 +000011778 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779}
11780
INADA Naoki3ae20562017-01-16 20:41:20 +090011781/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011782str.isascii as unicode_isascii
11783
11784Return True if all characters in the string are ASCII, False otherwise.
11785
11786ASCII characters have code points in the range U+0000-U+007F.
11787Empty string is ASCII too.
11788[clinic start generated code]*/
11789
11790static PyObject *
11791unicode_isascii_impl(PyObject *self)
11792/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11793{
11794 if (PyUnicode_READY(self) == -1) {
11795 return NULL;
11796 }
11797 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11798}
11799
11800/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011801str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011802
INADA Naoki3ae20562017-01-16 20:41:20 +090011803Return True if the string is a lowercase string, False otherwise.
11804
11805A string is lowercase if all cased characters in the string are lowercase and
11806there is at least one cased character in the string.
11807[clinic start generated code]*/
11808
11809static PyObject *
11810unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011811/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011812{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011813 Py_ssize_t i, length;
11814 int kind;
11815 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011816 int cased;
11817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 if (PyUnicode_READY(self) == -1)
11819 return NULL;
11820 length = PyUnicode_GET_LENGTH(self);
11821 kind = PyUnicode_KIND(self);
11822 data = PyUnicode_DATA(self);
11823
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 if (length == 1)
11826 return PyBool_FromLong(
11827 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011829 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011831 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011832
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 for (i = 0; i < length; i++) {
11835 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011836
Benjamin Peterson29060642009-01-31 22:14:21 +000011837 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011838 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011839 else if (!cased && Py_UNICODE_ISLOWER(ch))
11840 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011842 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843}
11844
INADA Naoki3ae20562017-01-16 20:41:20 +090011845/*[clinic input]
11846str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847
INADA Naoki3ae20562017-01-16 20:41:20 +090011848Return True if the string is an uppercase string, False otherwise.
11849
11850A string is uppercase if all cased characters in the string are uppercase and
11851there is at least one cased character in the string.
11852[clinic start generated code]*/
11853
11854static PyObject *
11855unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011856/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011857{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011858 Py_ssize_t i, length;
11859 int kind;
11860 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861 int cased;
11862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 if (PyUnicode_READY(self) == -1)
11864 return NULL;
11865 length = PyUnicode_GET_LENGTH(self);
11866 kind = PyUnicode_KIND(self);
11867 data = PyUnicode_DATA(self);
11868
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 if (length == 1)
11871 return PyBool_FromLong(
11872 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011874 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011876 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011877
Guido van Rossumd57fd912000-03-10 22:53:23 +000011878 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011879 for (i = 0; i < length; i++) {
11880 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011881
Benjamin Peterson29060642009-01-31 22:14:21 +000011882 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011883 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011884 else if (!cased && Py_UNICODE_ISUPPER(ch))
11885 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011887 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888}
11889
INADA Naoki3ae20562017-01-16 20:41:20 +090011890/*[clinic input]
11891str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892
INADA Naoki3ae20562017-01-16 20:41:20 +090011893Return True if the string is a title-cased string, False otherwise.
11894
11895In a title-cased string, upper- and title-case characters may only
11896follow uncased characters and lowercase characters only cased ones.
11897[clinic start generated code]*/
11898
11899static PyObject *
11900unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011901/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 Py_ssize_t i, length;
11904 int kind;
11905 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906 int cased, previous_is_cased;
11907
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011908 if (PyUnicode_READY(self) == -1)
11909 return NULL;
11910 length = PyUnicode_GET_LENGTH(self);
11911 kind = PyUnicode_KIND(self);
11912 data = PyUnicode_DATA(self);
11913
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 if (length == 1) {
11916 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11917 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11918 (Py_UNICODE_ISUPPER(ch) != 0));
11919 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011921 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011922 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011923 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011924
Guido van Rossumd57fd912000-03-10 22:53:23 +000011925 cased = 0;
11926 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011927 for (i = 0; i < length; i++) {
11928 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011929
Benjamin Peterson29060642009-01-31 22:14:21 +000011930 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11931 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011932 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011933 previous_is_cased = 1;
11934 cased = 1;
11935 }
11936 else if (Py_UNICODE_ISLOWER(ch)) {
11937 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011938 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011939 previous_is_cased = 1;
11940 cased = 1;
11941 }
11942 else
11943 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011945 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011946}
11947
INADA Naoki3ae20562017-01-16 20:41:20 +090011948/*[clinic input]
11949str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950
INADA Naoki3ae20562017-01-16 20:41:20 +090011951Return True if the string is a whitespace string, False otherwise.
11952
11953A string is whitespace if all characters in the string are whitespace and there
11954is at least one character in the string.
11955[clinic start generated code]*/
11956
11957static PyObject *
11958unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011959/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 Py_ssize_t i, length;
11962 int kind;
11963 void *data;
11964
11965 if (PyUnicode_READY(self) == -1)
11966 return NULL;
11967 length = PyUnicode_GET_LENGTH(self);
11968 kind = PyUnicode_KIND(self);
11969 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970
Guido van Rossumd57fd912000-03-10 22:53:23 +000011971 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 if (length == 1)
11973 return PyBool_FromLong(
11974 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011976 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011977 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011978 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 for (i = 0; i < length; i++) {
11981 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011982 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011983 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011984 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011985 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011986}
11987
INADA Naoki3ae20562017-01-16 20:41:20 +090011988/*[clinic input]
11989str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011990
INADA Naoki3ae20562017-01-16 20:41:20 +090011991Return True if the string is an alphabetic string, False otherwise.
11992
11993A string is alphabetic if all characters in the string are alphabetic and there
11994is at least one character in the string.
11995[clinic start generated code]*/
11996
11997static PyObject *
11998unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011999/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012000{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 Py_ssize_t i, length;
12002 int kind;
12003 void *data;
12004
12005 if (PyUnicode_READY(self) == -1)
12006 return NULL;
12007 length = PyUnicode_GET_LENGTH(self);
12008 kind = PyUnicode_KIND(self);
12009 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012010
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012011 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012012 if (length == 1)
12013 return PyBool_FromLong(
12014 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012015
12016 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012017 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012018 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012019
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 for (i = 0; i < length; i++) {
12021 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012022 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012023 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012024 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012025}
12026
INADA Naoki3ae20562017-01-16 20:41:20 +090012027/*[clinic input]
12028str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012029
INADA Naoki3ae20562017-01-16 20:41:20 +090012030Return True if the string is an alpha-numeric string, False otherwise.
12031
12032A string is alpha-numeric if all characters in the string are alpha-numeric and
12033there is at least one character in the string.
12034[clinic start generated code]*/
12035
12036static PyObject *
12037unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012038/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 int kind;
12041 void *data;
12042 Py_ssize_t len, i;
12043
12044 if (PyUnicode_READY(self) == -1)
12045 return NULL;
12046
12047 kind = PyUnicode_KIND(self);
12048 data = PyUnicode_DATA(self);
12049 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012050
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012051 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012052 if (len == 1) {
12053 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12054 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12055 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012056
12057 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012059 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012060
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 for (i = 0; i < len; i++) {
12062 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012063 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012064 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012065 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012066 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012067}
12068
INADA Naoki3ae20562017-01-16 20:41:20 +090012069/*[clinic input]
12070str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000012071
INADA Naoki3ae20562017-01-16 20:41:20 +090012072Return True if the string is a decimal string, False otherwise.
12073
12074A string is a decimal string if all characters in the string are decimal and
12075there is at least one character in the string.
12076[clinic start generated code]*/
12077
12078static PyObject *
12079unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012080/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 Py_ssize_t i, length;
12083 int kind;
12084 void *data;
12085
12086 if (PyUnicode_READY(self) == -1)
12087 return NULL;
12088 length = PyUnicode_GET_LENGTH(self);
12089 kind = PyUnicode_KIND(self);
12090 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012093 if (length == 1)
12094 return PyBool_FromLong(
12095 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012097 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012098 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012099 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012101 for (i = 0; i < length; i++) {
12102 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012103 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012104 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012105 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106}
12107
INADA Naoki3ae20562017-01-16 20:41:20 +090012108/*[clinic input]
12109str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110
INADA Naoki3ae20562017-01-16 20:41:20 +090012111Return True if the string is a digit string, False otherwise.
12112
12113A string is a digit string if all characters in the string are digits and there
12114is at least one character in the string.
12115[clinic start generated code]*/
12116
12117static PyObject *
12118unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012119/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 Py_ssize_t i, length;
12122 int kind;
12123 void *data;
12124
12125 if (PyUnicode_READY(self) == -1)
12126 return NULL;
12127 length = PyUnicode_GET_LENGTH(self);
12128 kind = PyUnicode_KIND(self);
12129 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012130
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012132 if (length == 1) {
12133 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12134 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12135 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012136
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012137 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012139 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012141 for (i = 0; i < length; i++) {
12142 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012143 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012145 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146}
12147
INADA Naoki3ae20562017-01-16 20:41:20 +090012148/*[clinic input]
12149str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150
INADA Naoki3ae20562017-01-16 20:41:20 +090012151Return True if the string is a numeric string, False otherwise.
12152
12153A string is numeric if all characters in the string are numeric and there is at
12154least one character in the string.
12155[clinic start generated code]*/
12156
12157static PyObject *
12158unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012159/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161 Py_ssize_t i, length;
12162 int kind;
12163 void *data;
12164
12165 if (PyUnicode_READY(self) == -1)
12166 return NULL;
12167 length = PyUnicode_GET_LENGTH(self);
12168 kind = PyUnicode_KIND(self);
12169 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012170
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012172 if (length == 1)
12173 return PyBool_FromLong(
12174 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012176 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012177 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012178 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 for (i = 0; i < length; i++) {
12181 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012182 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012184 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185}
12186
Martin v. Löwis47383402007-08-15 07:32:56 +000012187int
12188PyUnicode_IsIdentifier(PyObject *self)
12189{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190 int kind;
12191 void *data;
12192 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012193 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 if (PyUnicode_READY(self) == -1) {
12196 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012197 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012198 }
12199
12200 /* Special case for empty strings */
12201 if (PyUnicode_GET_LENGTH(self) == 0)
12202 return 0;
12203 kind = PyUnicode_KIND(self);
12204 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012205
12206 /* PEP 3131 says that the first character must be in
12207 XID_Start and subsequent characters in XID_Continue,
12208 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012209 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012210 letters, digits, underscore). However, given the current
12211 definition of XID_Start and XID_Continue, it is sufficient
12212 to check just for these, except that _ must be allowed
12213 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012215 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012216 return 0;
12217
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012218 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012219 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012220 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012221 return 1;
12222}
12223
INADA Naoki3ae20562017-01-16 20:41:20 +090012224/*[clinic input]
12225str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012226
INADA Naoki3ae20562017-01-16 20:41:20 +090012227Return True if the string is a valid Python identifier, False otherwise.
12228
Sanyam Khuranaffc5a142018-10-08 12:23:32 +053012229Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012230such as "def" or "class".
INADA Naoki3ae20562017-01-16 20:41:20 +090012231[clinic start generated code]*/
12232
12233static PyObject *
12234unicode_isidentifier_impl(PyObject *self)
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012235/*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012236{
12237 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12238}
12239
INADA Naoki3ae20562017-01-16 20:41:20 +090012240/*[clinic input]
12241str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012242
INADA Naoki3ae20562017-01-16 20:41:20 +090012243Return True if the string is printable, False otherwise.
12244
12245A string is printable if all of its characters are considered printable in
12246repr() or if it is empty.
12247[clinic start generated code]*/
12248
12249static PyObject *
12250unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012251/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012252{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253 Py_ssize_t i, length;
12254 int kind;
12255 void *data;
12256
12257 if (PyUnicode_READY(self) == -1)
12258 return NULL;
12259 length = PyUnicode_GET_LENGTH(self);
12260 kind = PyUnicode_KIND(self);
12261 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012262
12263 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012264 if (length == 1)
12265 return PyBool_FromLong(
12266 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012268 for (i = 0; i < length; i++) {
12269 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012270 Py_RETURN_FALSE;
12271 }
12272 }
12273 Py_RETURN_TRUE;
12274}
12275
INADA Naoki3ae20562017-01-16 20:41:20 +090012276/*[clinic input]
12277str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012278
INADA Naoki3ae20562017-01-16 20:41:20 +090012279 iterable: object
12280 /
12281
12282Concatenate any number of strings.
12283
Martin Panter91a88662017-01-24 00:30:06 +000012284The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012285The result is returned as a new string.
12286
12287Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12288[clinic start generated code]*/
12289
12290static PyObject *
12291unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012292/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293{
INADA Naoki3ae20562017-01-16 20:41:20 +090012294 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295}
12296
Martin v. Löwis18e16552006-02-15 17:27:45 +000012297static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012298unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012299{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300 if (PyUnicode_READY(self) == -1)
12301 return -1;
12302 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303}
12304
INADA Naoki3ae20562017-01-16 20:41:20 +090012305/*[clinic input]
12306str.ljust as unicode_ljust
12307
12308 width: Py_ssize_t
12309 fillchar: Py_UCS4 = ' '
12310 /
12311
12312Return a left-justified string of length width.
12313
12314Padding is done using the specified fill character (default is a space).
12315[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012316
12317static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012318unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12319/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012320{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012321 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012322 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012323
Victor Stinnerc4b49542011-12-11 22:44:26 +010012324 if (PyUnicode_GET_LENGTH(self) >= width)
12325 return unicode_result_unchanged(self);
12326
12327 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012328}
12329
INADA Naoki3ae20562017-01-16 20:41:20 +090012330/*[clinic input]
12331str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012332
INADA Naoki3ae20562017-01-16 20:41:20 +090012333Return a copy of the string converted to lowercase.
12334[clinic start generated code]*/
12335
12336static PyObject *
12337unicode_lower_impl(PyObject *self)
12338/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012340 if (PyUnicode_READY(self) == -1)
12341 return NULL;
12342 if (PyUnicode_IS_ASCII(self))
12343 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012344 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012345}
12346
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012347#define LEFTSTRIP 0
12348#define RIGHTSTRIP 1
12349#define BOTHSTRIP 2
12350
12351/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012352static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012353
INADA Naoki3ae20562017-01-16 20:41:20 +090012354#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012355
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012356/* externally visible for str.strip(unicode) */
12357PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012358_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012359{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012360 void *data;
12361 int kind;
12362 Py_ssize_t i, j, len;
12363 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012364 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012366 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12367 return NULL;
12368
12369 kind = PyUnicode_KIND(self);
12370 data = PyUnicode_DATA(self);
12371 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012372 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012373 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12374 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012375 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012376
Benjamin Peterson14339b62009-01-31 16:36:08 +000012377 i = 0;
12378 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012379 while (i < len) {
12380 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12381 if (!BLOOM(sepmask, ch))
12382 break;
12383 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12384 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012385 i++;
12386 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012387 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012388
Benjamin Peterson14339b62009-01-31 16:36:08 +000012389 j = len;
12390 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012391 j--;
12392 while (j >= i) {
12393 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12394 if (!BLOOM(sepmask, ch))
12395 break;
12396 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12397 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012398 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012399 }
12400
Benjamin Peterson29060642009-01-31 22:14:21 +000012401 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012402 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012403
Victor Stinner7931d9a2011-11-04 00:22:48 +010012404 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405}
12406
12407PyObject*
12408PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12409{
12410 unsigned char *data;
12411 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012412 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012413
Victor Stinnerde636f32011-10-01 03:55:54 +020012414 if (PyUnicode_READY(self) == -1)
12415 return NULL;
12416
Victor Stinner684d5fd2012-05-03 02:32:34 +020012417 length = PyUnicode_GET_LENGTH(self);
12418 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012419
Victor Stinner684d5fd2012-05-03 02:32:34 +020012420 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012421 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422
Victor Stinnerde636f32011-10-01 03:55:54 +020012423 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012424 PyErr_SetString(PyExc_IndexError, "string index out of range");
12425 return NULL;
12426 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012427 if (start >= length || end < start)
12428 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012429
Victor Stinner684d5fd2012-05-03 02:32:34 +020012430 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012431 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012432 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012433 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012434 }
12435 else {
12436 kind = PyUnicode_KIND(self);
12437 data = PyUnicode_1BYTE_DATA(self);
12438 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012439 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012440 length);
12441 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012442}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012443
12444static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012445do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012446{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012447 Py_ssize_t len, i, j;
12448
12449 if (PyUnicode_READY(self) == -1)
12450 return NULL;
12451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012452 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012453
Victor Stinnercc7af722013-04-09 22:39:24 +020012454 if (PyUnicode_IS_ASCII(self)) {
12455 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12456
12457 i = 0;
12458 if (striptype != RIGHTSTRIP) {
12459 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012460 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012461 if (!_Py_ascii_whitespace[ch])
12462 break;
12463 i++;
12464 }
12465 }
12466
12467 j = len;
12468 if (striptype != LEFTSTRIP) {
12469 j--;
12470 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012471 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012472 if (!_Py_ascii_whitespace[ch])
12473 break;
12474 j--;
12475 }
12476 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012477 }
12478 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012479 else {
12480 int kind = PyUnicode_KIND(self);
12481 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012482
Victor Stinnercc7af722013-04-09 22:39:24 +020012483 i = 0;
12484 if (striptype != RIGHTSTRIP) {
12485 while (i < len) {
12486 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12487 if (!Py_UNICODE_ISSPACE(ch))
12488 break;
12489 i++;
12490 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012491 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012492
12493 j = len;
12494 if (striptype != LEFTSTRIP) {
12495 j--;
12496 while (j >= i) {
12497 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12498 if (!Py_UNICODE_ISSPACE(ch))
12499 break;
12500 j--;
12501 }
12502 j++;
12503 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012504 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012505
Victor Stinner7931d9a2011-11-04 00:22:48 +010012506 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012507}
12508
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012509
12510static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012511do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012512{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012513 if (sep != NULL && sep != Py_None) {
12514 if (PyUnicode_Check(sep))
12515 return _PyUnicode_XStrip(self, striptype, sep);
12516 else {
12517 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012518 "%s arg must be None or str",
12519 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012520 return NULL;
12521 }
12522 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012523
Benjamin Peterson14339b62009-01-31 16:36:08 +000012524 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012525}
12526
12527
INADA Naoki3ae20562017-01-16 20:41:20 +090012528/*[clinic input]
12529str.strip as unicode_strip
12530
12531 chars: object = None
12532 /
12533
Victor Stinner0c4a8282017-01-17 02:21:47 +010012534Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012535
12536If chars is given and not None, remove characters in chars instead.
12537[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012538
12539static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012540unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012541/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012542{
INADA Naoki3ae20562017-01-16 20:41:20 +090012543 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012544}
12545
12546
INADA Naoki3ae20562017-01-16 20:41:20 +090012547/*[clinic input]
12548str.lstrip as unicode_lstrip
12549
12550 chars: object = NULL
12551 /
12552
12553Return a copy of the string with leading whitespace removed.
12554
12555If chars is given and not None, remove characters in chars instead.
12556[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012557
12558static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012559unicode_lstrip_impl(PyObject *self, PyObject *chars)
12560/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012561{
INADA Naoki3ae20562017-01-16 20:41:20 +090012562 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012563}
12564
12565
INADA Naoki3ae20562017-01-16 20:41:20 +090012566/*[clinic input]
12567str.rstrip as unicode_rstrip
12568
12569 chars: object = NULL
12570 /
12571
12572Return a copy of the string with trailing whitespace removed.
12573
12574If chars is given and not None, remove characters in chars instead.
12575[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012576
12577static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012578unicode_rstrip_impl(PyObject *self, PyObject *chars)
12579/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012580{
INADA Naoki3ae20562017-01-16 20:41:20 +090012581 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012582}
12583
12584
Guido van Rossumd57fd912000-03-10 22:53:23 +000012585static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012586unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012587{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012588 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012590
Serhiy Storchaka05997252013-01-26 12:14:02 +020012591 if (len < 1)
12592 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012593
Victor Stinnerc4b49542011-12-11 22:44:26 +010012594 /* no repeat, return original string */
12595 if (len == 1)
12596 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012597
Benjamin Petersonbac79492012-01-14 13:34:47 -050012598 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012599 return NULL;
12600
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012601 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012602 PyErr_SetString(PyExc_OverflowError,
12603 "repeated string is too long");
12604 return NULL;
12605 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012606 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012607
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012608 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609 if (!u)
12610 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012611 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613 if (PyUnicode_GET_LENGTH(str) == 1) {
12614 const int kind = PyUnicode_KIND(str);
12615 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012616 if (kind == PyUnicode_1BYTE_KIND) {
12617 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012618 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012619 }
12620 else if (kind == PyUnicode_2BYTE_KIND) {
12621 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012622 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012623 ucs2[n] = fill_char;
12624 } else {
12625 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12626 assert(kind == PyUnicode_4BYTE_KIND);
12627 for (n = 0; n < len; ++n)
12628 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630 }
12631 else {
12632 /* number of characters copied this far */
12633 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012634 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012636 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012638 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012640 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012641 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012642 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012643 }
12644
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012645 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012646 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647}
12648
Alexander Belopolsky40018472011-02-26 01:02:56 +000012649PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012650PyUnicode_Replace(PyObject *str,
12651 PyObject *substr,
12652 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012653 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012655 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12656 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012657 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012658 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659}
12660
INADA Naoki3ae20562017-01-16 20:41:20 +090012661/*[clinic input]
12662str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663
INADA Naoki3ae20562017-01-16 20:41:20 +090012664 old: unicode
12665 new: unicode
12666 count: Py_ssize_t = -1
12667 Maximum number of occurrences to replace.
12668 -1 (the default value) means replace all occurrences.
12669 /
12670
12671Return a copy with all occurrences of substring old replaced by new.
12672
12673If the optional argument count is given, only the first count occurrences are
12674replaced.
12675[clinic start generated code]*/
12676
12677static PyObject *
12678unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12679 Py_ssize_t count)
12680/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012682 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012683 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012684 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685}
12686
Alexander Belopolsky40018472011-02-26 01:02:56 +000012687static PyObject *
12688unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012690 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691 Py_ssize_t isize;
12692 Py_ssize_t osize, squote, dquote, i, o;
12693 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012694 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012695 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012696
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012697 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012698 return NULL;
12699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012700 isize = PyUnicode_GET_LENGTH(unicode);
12701 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012703 /* Compute length of output, quote characters, and
12704 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012705 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 max = 127;
12707 squote = dquote = 0;
12708 ikind = PyUnicode_KIND(unicode);
12709 for (i = 0; i < isize; i++) {
12710 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012711 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012712 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012713 case '\'': squote++; break;
12714 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012715 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012716 incr = 2;
12717 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012718 default:
12719 /* Fast-path ASCII */
12720 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012721 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012723 ;
12724 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012727 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012728 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012729 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012730 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012731 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012732 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012733 if (osize > PY_SSIZE_T_MAX - incr) {
12734 PyErr_SetString(PyExc_OverflowError,
12735 "string is too long to generate repr");
12736 return NULL;
12737 }
12738 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012739 }
12740
12741 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012742 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012743 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012744 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012745 if (dquote)
12746 /* Both squote and dquote present. Use squote,
12747 and escape them */
12748 osize += squote;
12749 else
12750 quote = '"';
12751 }
Victor Stinner55c08782013-04-14 18:45:39 +020012752 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012753
12754 repr = PyUnicode_New(osize, max);
12755 if (repr == NULL)
12756 return NULL;
12757 okind = PyUnicode_KIND(repr);
12758 odata = PyUnicode_DATA(repr);
12759
12760 PyUnicode_WRITE(okind, odata, 0, quote);
12761 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012762 if (unchanged) {
12763 _PyUnicode_FastCopyCharacters(repr, 1,
12764 unicode, 0,
12765 isize);
12766 }
12767 else {
12768 for (i = 0, o = 1; i < isize; i++) {
12769 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012770
Victor Stinner55c08782013-04-14 18:45:39 +020012771 /* Escape quotes and backslashes */
12772 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012773 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012775 continue;
12776 }
12777
12778 /* Map special whitespace to '\t', \n', '\r' */
12779 if (ch == '\t') {
12780 PyUnicode_WRITE(okind, odata, o++, '\\');
12781 PyUnicode_WRITE(okind, odata, o++, 't');
12782 }
12783 else if (ch == '\n') {
12784 PyUnicode_WRITE(okind, odata, o++, '\\');
12785 PyUnicode_WRITE(okind, odata, o++, 'n');
12786 }
12787 else if (ch == '\r') {
12788 PyUnicode_WRITE(okind, odata, o++, '\\');
12789 PyUnicode_WRITE(okind, odata, o++, 'r');
12790 }
12791
12792 /* Map non-printable US ASCII to '\xhh' */
12793 else if (ch < ' ' || ch == 0x7F) {
12794 PyUnicode_WRITE(okind, odata, o++, '\\');
12795 PyUnicode_WRITE(okind, odata, o++, 'x');
12796 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12797 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12798 }
12799
12800 /* Copy ASCII characters as-is */
12801 else if (ch < 0x7F) {
12802 PyUnicode_WRITE(okind, odata, o++, ch);
12803 }
12804
12805 /* Non-ASCII characters */
12806 else {
12807 /* Map Unicode whitespace and control characters
12808 (categories Z* and C* except ASCII space)
12809 */
12810 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12811 PyUnicode_WRITE(okind, odata, o++, '\\');
12812 /* Map 8-bit characters to '\xhh' */
12813 if (ch <= 0xff) {
12814 PyUnicode_WRITE(okind, odata, o++, 'x');
12815 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12816 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12817 }
12818 /* Map 16-bit characters to '\uxxxx' */
12819 else if (ch <= 0xffff) {
12820 PyUnicode_WRITE(okind, odata, o++, 'u');
12821 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12822 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12823 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12824 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12825 }
12826 /* Map 21-bit characters to '\U00xxxxxx' */
12827 else {
12828 PyUnicode_WRITE(okind, odata, o++, 'U');
12829 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12830 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12831 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12832 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12833 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12834 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12835 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12836 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12837 }
12838 }
12839 /* Copy characters as-is */
12840 else {
12841 PyUnicode_WRITE(okind, odata, o++, ch);
12842 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012843 }
12844 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012845 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012846 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012847 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012848 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849}
12850
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012851PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012852 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853\n\
12854Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012855such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012856arguments start and end are interpreted as in slice notation.\n\
12857\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012858Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859
12860static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012861unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012862{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012863 /* initialize variables to prevent gcc warning */
12864 PyObject *substring = NULL;
12865 Py_ssize_t start = 0;
12866 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012867 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012868
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012869 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012870 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012871
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012872 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012873 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012874
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012875 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012876
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012877 if (result == -2)
12878 return NULL;
12879
Christian Heimes217cfd12007-12-02 14:31:20 +000012880 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012881}
12882
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012883PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012884 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012885\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012886Return the highest index in S where substring sub is found,\n\
12887such that sub is contained within S[start:end]. Optional\n\
12888arguments start and end are interpreted as in slice notation.\n\
12889\n\
12890Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891
12892static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012893unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012894{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012895 /* initialize variables to prevent gcc warning */
12896 PyObject *substring = NULL;
12897 Py_ssize_t start = 0;
12898 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012899 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012901 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012902 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012904 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012905 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012906
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012907 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012908
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 if (result == -2)
12910 return NULL;
12911
Guido van Rossumd57fd912000-03-10 22:53:23 +000012912 if (result < 0) {
12913 PyErr_SetString(PyExc_ValueError, "substring not found");
12914 return NULL;
12915 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012916
Christian Heimes217cfd12007-12-02 14:31:20 +000012917 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012918}
12919
INADA Naoki3ae20562017-01-16 20:41:20 +090012920/*[clinic input]
12921str.rjust as unicode_rjust
12922
12923 width: Py_ssize_t
12924 fillchar: Py_UCS4 = ' '
12925 /
12926
12927Return a right-justified string of length width.
12928
12929Padding is done using the specified fill character (default is a space).
12930[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012931
12932static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012933unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12934/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012935{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012936 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012937 return NULL;
12938
Victor Stinnerc4b49542011-12-11 22:44:26 +010012939 if (PyUnicode_GET_LENGTH(self) >= width)
12940 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012941
Victor Stinnerc4b49542011-12-11 22:44:26 +010012942 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012943}
12944
Alexander Belopolsky40018472011-02-26 01:02:56 +000012945PyObject *
12946PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012947{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012948 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012949 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012950
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012951 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012952}
12953
INADA Naoki3ae20562017-01-16 20:41:20 +090012954/*[clinic input]
12955str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012956
INADA Naoki3ae20562017-01-16 20:41:20 +090012957 sep: object = None
12958 The delimiter according which to split the string.
12959 None (the default value) means split according to any whitespace,
12960 and discard empty strings from the result.
12961 maxsplit: Py_ssize_t = -1
12962 Maximum number of splits to do.
12963 -1 (the default value) means no limit.
12964
12965Return a list of the words in the string, using sep as the delimiter string.
12966[clinic start generated code]*/
12967
12968static PyObject *
12969unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12970/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012971{
INADA Naoki3ae20562017-01-16 20:41:20 +090012972 if (sep == Py_None)
12973 return split(self, NULL, maxsplit);
12974 if (PyUnicode_Check(sep))
12975 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012976
Victor Stinner998b8062018-09-12 00:23:25 +020012977 PyErr_Format(PyExc_TypeError,
12978 "must be str or None, not %.100s",
12979 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012980 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012981}
12982
Thomas Wouters477c8d52006-05-27 19:21:47 +000012983PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012984PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012985{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012986 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012987 int kind1, kind2;
12988 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012989 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012990
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012991 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012992 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012993
Victor Stinner14f8f022011-10-05 20:58:25 +020012994 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012995 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012996 len1 = PyUnicode_GET_LENGTH(str_obj);
12997 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012998 if (kind1 < kind2 || len1 < len2) {
12999 _Py_INCREF_UNICODE_EMPTY();
13000 if (!unicode_empty)
13001 out = NULL;
13002 else {
13003 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
13004 Py_DECREF(unicode_empty);
13005 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013006 return out;
13007 }
13008 buf1 = PyUnicode_DATA(str_obj);
13009 buf2 = PyUnicode_DATA(sep_obj);
13010 if (kind2 != kind1) {
13011 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13012 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013013 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013014 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013015
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013016 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013018 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13019 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13020 else
13021 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013022 break;
13023 case PyUnicode_2BYTE_KIND:
13024 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13025 break;
13026 case PyUnicode_4BYTE_KIND:
13027 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13028 break;
13029 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013030 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013031 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013032
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013033 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013034 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013035
13036 return out;
13037}
13038
13039
13040PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013041PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013042{
Thomas Wouters477c8d52006-05-27 19:21:47 +000013043 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013044 int kind1, kind2;
13045 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013046 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013047
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013048 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013049 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013050
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013051 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013052 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013053 len1 = PyUnicode_GET_LENGTH(str_obj);
13054 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013055 if (kind1 < kind2 || len1 < len2) {
13056 _Py_INCREF_UNICODE_EMPTY();
13057 if (!unicode_empty)
13058 out = NULL;
13059 else {
13060 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
13061 Py_DECREF(unicode_empty);
13062 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013063 return out;
13064 }
13065 buf1 = PyUnicode_DATA(str_obj);
13066 buf2 = PyUnicode_DATA(sep_obj);
13067 if (kind2 != kind1) {
13068 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13069 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013070 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013071 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013072
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013073 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013074 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013075 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13076 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13077 else
13078 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013079 break;
13080 case PyUnicode_2BYTE_KIND:
13081 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13082 break;
13083 case PyUnicode_4BYTE_KIND:
13084 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13085 break;
13086 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013087 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013088 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013089
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013090 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013091 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013092
13093 return out;
13094}
13095
INADA Naoki3ae20562017-01-16 20:41:20 +090013096/*[clinic input]
13097str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013098
INADA Naoki3ae20562017-01-16 20:41:20 +090013099 sep: object
13100 /
13101
13102Partition the string into three parts using the given separator.
13103
13104This will search for the separator in the string. If the separator is found,
13105returns a 3-tuple containing the part before the separator, the separator
13106itself, and the part after it.
13107
13108If the separator is not found, returns a 3-tuple containing the original string
13109and two empty strings.
13110[clinic start generated code]*/
13111
13112static PyObject *
13113unicode_partition(PyObject *self, PyObject *sep)
13114/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013115{
INADA Naoki3ae20562017-01-16 20:41:20 +090013116 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013117}
13118
INADA Naoki3ae20562017-01-16 20:41:20 +090013119/*[clinic input]
13120str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013121
INADA Naoki3ae20562017-01-16 20:41:20 +090013122Partition the string into three parts using the given separator.
13123
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013124This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090013125the separator is found, returns a 3-tuple containing the part before the
13126separator, the separator itself, and the part after it.
13127
13128If the separator is not found, returns a 3-tuple containing two empty strings
13129and the original string.
13130[clinic start generated code]*/
13131
13132static PyObject *
13133unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013134/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013135{
INADA Naoki3ae20562017-01-16 20:41:20 +090013136 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013137}
13138
Alexander Belopolsky40018472011-02-26 01:02:56 +000013139PyObject *
13140PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013141{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013142 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013143 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013144
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013145 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013146}
13147
INADA Naoki3ae20562017-01-16 20:41:20 +090013148/*[clinic input]
13149str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013150
INADA Naoki3ae20562017-01-16 20:41:20 +090013151Return a list of the words in the string, using sep as the delimiter string.
13152
13153Splits are done starting at the end of the string and working to the front.
13154[clinic start generated code]*/
13155
13156static PyObject *
13157unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13158/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013159{
INADA Naoki3ae20562017-01-16 20:41:20 +090013160 if (sep == Py_None)
13161 return rsplit(self, NULL, maxsplit);
13162 if (PyUnicode_Check(sep))
13163 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013164
Victor Stinner998b8062018-09-12 00:23:25 +020013165 PyErr_Format(PyExc_TypeError,
13166 "must be str or None, not %.100s",
13167 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013168 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013169}
13170
INADA Naoki3ae20562017-01-16 20:41:20 +090013171/*[clinic input]
13172str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013173
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013174 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013175
13176Return a list of the lines in the string, breaking at line boundaries.
13177
13178Line breaks are not included in the resulting list unless keepends is given and
13179true.
13180[clinic start generated code]*/
13181
13182static PyObject *
13183unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013184/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013185{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013186 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187}
13188
13189static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013190PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013192 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193}
13194
INADA Naoki3ae20562017-01-16 20:41:20 +090013195/*[clinic input]
13196str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197
INADA Naoki3ae20562017-01-16 20:41:20 +090013198Convert uppercase characters to lowercase and lowercase characters to uppercase.
13199[clinic start generated code]*/
13200
13201static PyObject *
13202unicode_swapcase_impl(PyObject *self)
13203/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013204{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013205 if (PyUnicode_READY(self) == -1)
13206 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013207 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208}
13209
Larry Hastings61272b72014-01-07 12:41:53 -080013210/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013211
Larry Hastings31826802013-10-19 00:09:25 -070013212@staticmethod
13213str.maketrans as unicode_maketrans
13214
13215 x: object
13216
13217 y: unicode=NULL
13218
13219 z: unicode=NULL
13220
13221 /
13222
13223Return a translation table usable for str.translate().
13224
13225If there is only one argument, it must be a dictionary mapping Unicode
13226ordinals (integers) or characters to Unicode ordinals, strings or None.
13227Character keys will be then converted to ordinals.
13228If there are two arguments, they must be strings of equal length, and
13229in the resulting dictionary, each character in x will be mapped to the
13230character at the same position in y. If there is a third argument, it
13231must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013232[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013233
Larry Hastings31826802013-10-19 00:09:25 -070013234static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013235unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013236/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013237{
Georg Brandlceee0772007-11-27 23:48:05 +000013238 PyObject *new = NULL, *key, *value;
13239 Py_ssize_t i = 0;
13240 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013241
Georg Brandlceee0772007-11-27 23:48:05 +000013242 new = PyDict_New();
13243 if (!new)
13244 return NULL;
13245 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013246 int x_kind, y_kind, z_kind;
13247 void *x_data, *y_data, *z_data;
13248
Georg Brandlceee0772007-11-27 23:48:05 +000013249 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013250 if (!PyUnicode_Check(x)) {
13251 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13252 "be a string if there is a second argument");
13253 goto err;
13254 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013255 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013256 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13257 "arguments must have equal length");
13258 goto err;
13259 }
13260 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013261 x_kind = PyUnicode_KIND(x);
13262 y_kind = PyUnicode_KIND(y);
13263 x_data = PyUnicode_DATA(x);
13264 y_data = PyUnicode_DATA(y);
13265 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13266 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013267 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013268 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013269 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013270 if (!value) {
13271 Py_DECREF(key);
13272 goto err;
13273 }
Georg Brandlceee0772007-11-27 23:48:05 +000013274 res = PyDict_SetItem(new, key, value);
13275 Py_DECREF(key);
13276 Py_DECREF(value);
13277 if (res < 0)
13278 goto err;
13279 }
13280 /* create entries for deleting chars in z */
13281 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013282 z_kind = PyUnicode_KIND(z);
13283 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013284 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013285 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013286 if (!key)
13287 goto err;
13288 res = PyDict_SetItem(new, key, Py_None);
13289 Py_DECREF(key);
13290 if (res < 0)
13291 goto err;
13292 }
13293 }
13294 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013295 int kind;
13296 void *data;
13297
Georg Brandlceee0772007-11-27 23:48:05 +000013298 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013299 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013300 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13301 "to maketrans it must be a dict");
13302 goto err;
13303 }
13304 /* copy entries into the new dict, converting string keys to int keys */
13305 while (PyDict_Next(x, &i, &key, &value)) {
13306 if (PyUnicode_Check(key)) {
13307 /* convert string keys to integer keys */
13308 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013309 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013310 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13311 "table must be of length 1");
13312 goto err;
13313 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013314 kind = PyUnicode_KIND(key);
13315 data = PyUnicode_DATA(key);
13316 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013317 if (!newkey)
13318 goto err;
13319 res = PyDict_SetItem(new, newkey, value);
13320 Py_DECREF(newkey);
13321 if (res < 0)
13322 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013323 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013324 /* just keep integer keys */
13325 if (PyDict_SetItem(new, key, value) < 0)
13326 goto err;
13327 } else {
13328 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13329 "be strings or integers");
13330 goto err;
13331 }
13332 }
13333 }
13334 return new;
13335 err:
13336 Py_DECREF(new);
13337 return NULL;
13338}
13339
INADA Naoki3ae20562017-01-16 20:41:20 +090013340/*[clinic input]
13341str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013342
INADA Naoki3ae20562017-01-16 20:41:20 +090013343 table: object
13344 Translation table, which must be a mapping of Unicode ordinals to
13345 Unicode ordinals, strings, or None.
13346 /
13347
13348Replace each character in the string using the given translation table.
13349
13350The table must implement lookup/indexing via __getitem__, for instance a
13351dictionary or list. If this operation raises LookupError, the character is
13352left untouched. Characters mapped to None are deleted.
13353[clinic start generated code]*/
13354
13355static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013356unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013357/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013358{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013359 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013360}
13361
INADA Naoki3ae20562017-01-16 20:41:20 +090013362/*[clinic input]
13363str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013364
INADA Naoki3ae20562017-01-16 20:41:20 +090013365Return a copy of the string converted to uppercase.
13366[clinic start generated code]*/
13367
13368static PyObject *
13369unicode_upper_impl(PyObject *self)
13370/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013371{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013372 if (PyUnicode_READY(self) == -1)
13373 return NULL;
13374 if (PyUnicode_IS_ASCII(self))
13375 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013376 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013377}
13378
INADA Naoki3ae20562017-01-16 20:41:20 +090013379/*[clinic input]
13380str.zfill as unicode_zfill
13381
13382 width: Py_ssize_t
13383 /
13384
13385Pad a numeric string with zeros on the left, to fill a field of the given width.
13386
13387The string is never truncated.
13388[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013389
13390static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013391unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013392/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013393{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013394 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013395 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013396 int kind;
13397 void *data;
13398 Py_UCS4 chr;
13399
Benjamin Petersonbac79492012-01-14 13:34:47 -050013400 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013401 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402
Victor Stinnerc4b49542011-12-11 22:44:26 +010013403 if (PyUnicode_GET_LENGTH(self) >= width)
13404 return unicode_result_unchanged(self);
13405
13406 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013407
13408 u = pad(self, fill, 0, '0');
13409
Walter Dörwald068325e2002-04-15 13:36:47 +000013410 if (u == NULL)
13411 return NULL;
13412
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013413 kind = PyUnicode_KIND(u);
13414 data = PyUnicode_DATA(u);
13415 chr = PyUnicode_READ(kind, data, fill);
13416
13417 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013418 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013419 PyUnicode_WRITE(kind, data, 0, chr);
13420 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013421 }
13422
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013423 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013424 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013425}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013426
13427#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013428static PyObject *
13429unicode__decimal2ascii(PyObject *self)
13430{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013431 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013432}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013433#endif
13434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013435PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013436 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013437\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013438Return True if S starts with the specified prefix, False otherwise.\n\
13439With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013440With optional end, stop comparing S at that position.\n\
13441prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013442
13443static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013444unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013445 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013446{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013447 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013448 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013449 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013450 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013451 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013452
Jesus Ceaac451502011-04-20 17:09:23 +020013453 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013454 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013455 if (PyTuple_Check(subobj)) {
13456 Py_ssize_t i;
13457 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013458 substring = PyTuple_GET_ITEM(subobj, i);
13459 if (!PyUnicode_Check(substring)) {
13460 PyErr_Format(PyExc_TypeError,
13461 "tuple for startswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013462 "not %.100s",
13463 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013464 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013465 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013466 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013467 if (result == -1)
13468 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013469 if (result) {
13470 Py_RETURN_TRUE;
13471 }
13472 }
13473 /* nothing matched */
13474 Py_RETURN_FALSE;
13475 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013476 if (!PyUnicode_Check(subobj)) {
13477 PyErr_Format(PyExc_TypeError,
13478 "startswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013479 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013480 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013481 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013482 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013483 if (result == -1)
13484 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013485 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013486}
13487
13488
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013489PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013490 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013491\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013492Return True if S ends with the specified suffix, False otherwise.\n\
13493With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013494With optional end, stop comparing S at that position.\n\
13495suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013496
13497static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013498unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013499 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013500{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013501 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013502 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013503 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013504 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013505 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013506
Jesus Ceaac451502011-04-20 17:09:23 +020013507 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013509 if (PyTuple_Check(subobj)) {
13510 Py_ssize_t i;
13511 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013512 substring = PyTuple_GET_ITEM(subobj, i);
13513 if (!PyUnicode_Check(substring)) {
13514 PyErr_Format(PyExc_TypeError,
13515 "tuple for endswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013516 "not %.100s",
13517 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013518 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013519 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013520 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013521 if (result == -1)
13522 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013523 if (result) {
13524 Py_RETURN_TRUE;
13525 }
13526 }
13527 Py_RETURN_FALSE;
13528 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013529 if (!PyUnicode_Check(subobj)) {
13530 PyErr_Format(PyExc_TypeError,
13531 "endswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013532 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013533 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013534 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013535 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013536 if (result == -1)
13537 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013538 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013539}
13540
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013541static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013542_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013543{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013544 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13545 writer->data = PyUnicode_DATA(writer->buffer);
13546
13547 if (!writer->readonly) {
13548 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013549 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013550 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013551 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013552 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13553 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13554 writer->kind = PyUnicode_WCHAR_KIND;
13555 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13556
Victor Stinner8f674cc2013-04-17 23:02:17 +020013557 /* Copy-on-write mode: set buffer size to 0 so
13558 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13559 * next write. */
13560 writer->size = 0;
13561 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013562}
13563
Victor Stinnerd3f08822012-05-29 12:57:52 +020013564void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013565_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013566{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013567 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013568
13569 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013570 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013571
13572 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13573 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13574 writer->kind = PyUnicode_WCHAR_KIND;
13575 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013576}
13577
Inada Naoki770847a2019-06-24 12:30:24 +090013578// Initialize _PyUnicodeWriter with initial buffer
13579static inline void
13580_PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer)
13581{
13582 memset(writer, 0, sizeof(*writer));
13583 writer->buffer = buffer;
13584 _PyUnicodeWriter_Update(writer);
13585 writer->min_length = writer->size;
13586}
13587
Victor Stinnerd3f08822012-05-29 12:57:52 +020013588int
13589_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13590 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013591{
13592 Py_ssize_t newlen;
13593 PyObject *newbuffer;
13594
Victor Stinner2740e462016-09-06 16:58:36 -070013595 assert(maxchar <= MAX_UNICODE);
13596
Victor Stinnerca9381e2015-09-22 00:58:32 +020013597 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013598 assert((maxchar > writer->maxchar && length >= 0)
13599 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013600
Victor Stinner202fdca2012-05-07 12:47:02 +020013601 if (length > PY_SSIZE_T_MAX - writer->pos) {
13602 PyErr_NoMemory();
13603 return -1;
13604 }
13605 newlen = writer->pos + length;
13606
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013607 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013608
Victor Stinnerd3f08822012-05-29 12:57:52 +020013609 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013610 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013611 if (writer->overallocate
13612 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13613 /* overallocate to limit the number of realloc() */
13614 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013615 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013616 if (newlen < writer->min_length)
13617 newlen = writer->min_length;
13618
Victor Stinnerd3f08822012-05-29 12:57:52 +020013619 writer->buffer = PyUnicode_New(newlen, maxchar);
13620 if (writer->buffer == NULL)
13621 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013622 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013623 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013624 if (writer->overallocate
13625 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13626 /* overallocate to limit the number of realloc() */
13627 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013628 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013629 if (newlen < writer->min_length)
13630 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013631
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013632 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013633 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013634 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013635 newbuffer = PyUnicode_New(newlen, maxchar);
13636 if (newbuffer == NULL)
13637 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013638 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13639 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013640 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013641 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013642 }
13643 else {
13644 newbuffer = resize_compact(writer->buffer, newlen);
13645 if (newbuffer == NULL)
13646 return -1;
13647 }
13648 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013649 }
13650 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013651 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013652 newbuffer = PyUnicode_New(writer->size, maxchar);
13653 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013654 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013655 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13656 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013657 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013658 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013659 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013660 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013661
13662#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013663}
13664
Victor Stinnerca9381e2015-09-22 00:58:32 +020013665int
13666_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13667 enum PyUnicode_Kind kind)
13668{
13669 Py_UCS4 maxchar;
13670
13671 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13672 assert(writer->kind < kind);
13673
13674 switch (kind)
13675 {
13676 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13677 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13678 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13679 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013680 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013681 }
13682
13683 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13684}
13685
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013686static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013687_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013688{
Victor Stinner2740e462016-09-06 16:58:36 -070013689 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013690 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13691 return -1;
13692 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13693 writer->pos++;
13694 return 0;
13695}
13696
13697int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013698_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13699{
13700 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13701}
13702
13703int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013704_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13705{
13706 Py_UCS4 maxchar;
13707 Py_ssize_t len;
13708
13709 if (PyUnicode_READY(str) == -1)
13710 return -1;
13711 len = PyUnicode_GET_LENGTH(str);
13712 if (len == 0)
13713 return 0;
13714 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13715 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013716 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013717 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013718 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013719 Py_INCREF(str);
13720 writer->buffer = str;
13721 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013722 writer->pos += len;
13723 return 0;
13724 }
13725 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13726 return -1;
13727 }
13728 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13729 str, 0, len);
13730 writer->pos += len;
13731 return 0;
13732}
13733
Victor Stinnere215d962012-10-06 23:03:36 +020013734int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013735_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13736 Py_ssize_t start, Py_ssize_t end)
13737{
13738 Py_UCS4 maxchar;
13739 Py_ssize_t len;
13740
13741 if (PyUnicode_READY(str) == -1)
13742 return -1;
13743
13744 assert(0 <= start);
13745 assert(end <= PyUnicode_GET_LENGTH(str));
13746 assert(start <= end);
13747
13748 if (end == 0)
13749 return 0;
13750
13751 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13752 return _PyUnicodeWriter_WriteStr(writer, str);
13753
13754 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13755 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13756 else
13757 maxchar = writer->maxchar;
13758 len = end - start;
13759
13760 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13761 return -1;
13762
13763 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13764 str, start, len);
13765 writer->pos += len;
13766 return 0;
13767}
13768
13769int
Victor Stinner4a587072013-11-19 12:54:53 +010013770_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13771 const char *ascii, Py_ssize_t len)
13772{
13773 if (len == -1)
13774 len = strlen(ascii);
13775
13776 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13777
13778 if (writer->buffer == NULL && !writer->overallocate) {
13779 PyObject *str;
13780
13781 str = _PyUnicode_FromASCII(ascii, len);
13782 if (str == NULL)
13783 return -1;
13784
13785 writer->readonly = 1;
13786 writer->buffer = str;
13787 _PyUnicodeWriter_Update(writer);
13788 writer->pos += len;
13789 return 0;
13790 }
13791
13792 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13793 return -1;
13794
13795 switch (writer->kind)
13796 {
13797 case PyUnicode_1BYTE_KIND:
13798 {
13799 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13800 Py_UCS1 *data = writer->data;
13801
Christian Heimesf051e432016-09-13 20:22:02 +020013802 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013803 break;
13804 }
13805 case PyUnicode_2BYTE_KIND:
13806 {
13807 _PyUnicode_CONVERT_BYTES(
13808 Py_UCS1, Py_UCS2,
13809 ascii, ascii + len,
13810 (Py_UCS2 *)writer->data + writer->pos);
13811 break;
13812 }
13813 case PyUnicode_4BYTE_KIND:
13814 {
13815 _PyUnicode_CONVERT_BYTES(
13816 Py_UCS1, Py_UCS4,
13817 ascii, ascii + len,
13818 (Py_UCS4 *)writer->data + writer->pos);
13819 break;
13820 }
13821 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013822 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013823 }
13824
13825 writer->pos += len;
13826 return 0;
13827}
13828
13829int
13830_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13831 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013832{
13833 Py_UCS4 maxchar;
13834
13835 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13836 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13837 return -1;
13838 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13839 writer->pos += len;
13840 return 0;
13841}
13842
Victor Stinnerd3f08822012-05-29 12:57:52 +020013843PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013844_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013845{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013846 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013847
Victor Stinnerd3f08822012-05-29 12:57:52 +020013848 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013849 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013850 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013851 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013852
13853 str = writer->buffer;
13854 writer->buffer = NULL;
13855
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013856 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013857 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13858 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013859 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013860
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013861 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13862 PyObject *str2;
13863 str2 = resize_compact(str, writer->pos);
13864 if (str2 == NULL) {
13865 Py_DECREF(str);
13866 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013867 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013868 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013869 }
13870
Victor Stinner15a0bd32013-07-08 22:29:55 +020013871 assert(_PyUnicode_CheckConsistency(str, 1));
13872 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013873}
13874
Victor Stinnerd3f08822012-05-29 12:57:52 +020013875void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013876_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013877{
13878 Py_CLEAR(writer->buffer);
13879}
13880
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013881#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013882
13883PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013884 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013885\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013886Return a formatted version of S, using substitutions from args and kwargs.\n\
13887The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013888
Eric Smith27bbca62010-11-04 17:06:58 +000013889PyDoc_STRVAR(format_map__doc__,
13890 "S.format_map(mapping) -> str\n\
13891\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013892Return a formatted version of S, using substitutions from mapping.\n\
13893The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013894
INADA Naoki3ae20562017-01-16 20:41:20 +090013895/*[clinic input]
13896str.__format__ as unicode___format__
13897
13898 format_spec: unicode
13899 /
13900
13901Return a formatted version of the string as described by format_spec.
13902[clinic start generated code]*/
13903
Eric Smith4a7d76d2008-05-30 18:10:19 +000013904static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013905unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013906/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013907{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013908 _PyUnicodeWriter writer;
13909 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013910
Victor Stinnerd3f08822012-05-29 12:57:52 +020013911 if (PyUnicode_READY(self) == -1)
13912 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013913 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013914 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13915 self, format_spec, 0,
13916 PyUnicode_GET_LENGTH(format_spec));
13917 if (ret == -1) {
13918 _PyUnicodeWriter_Dealloc(&writer);
13919 return NULL;
13920 }
13921 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013922}
13923
INADA Naoki3ae20562017-01-16 20:41:20 +090013924/*[clinic input]
13925str.__sizeof__ as unicode_sizeof
13926
13927Return the size of the string in memory, in bytes.
13928[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013929
13930static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013931unicode_sizeof_impl(PyObject *self)
13932/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013934 Py_ssize_t size;
13935
13936 /* If it's a compact object, account for base structure +
13937 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013938 if (PyUnicode_IS_COMPACT_ASCII(self))
13939 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13940 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013941 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013942 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013943 else {
13944 /* If it is a two-block object, account for base object, and
13945 for character block if present. */
13946 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013947 if (_PyUnicode_DATA_ANY(self))
13948 size += (PyUnicode_GET_LENGTH(self) + 1) *
13949 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013950 }
13951 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013952 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013953 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13954 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13955 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13956 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013957
13958 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013959}
13960
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013961static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013962unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013963{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013964 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013965 if (!copy)
13966 return NULL;
13967 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013968}
13969
Guido van Rossumd57fd912000-03-10 22:53:23 +000013970static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013971 UNICODE_ENCODE_METHODDEF
13972 UNICODE_REPLACE_METHODDEF
13973 UNICODE_SPLIT_METHODDEF
13974 UNICODE_RSPLIT_METHODDEF
13975 UNICODE_JOIN_METHODDEF
13976 UNICODE_CAPITALIZE_METHODDEF
13977 UNICODE_CASEFOLD_METHODDEF
13978 UNICODE_TITLE_METHODDEF
13979 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013980 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013981 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013982 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013983 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013984 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013985 UNICODE_LJUST_METHODDEF
13986 UNICODE_LOWER_METHODDEF
13987 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013988 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13989 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013990 UNICODE_RJUST_METHODDEF
13991 UNICODE_RSTRIP_METHODDEF
13992 UNICODE_RPARTITION_METHODDEF
13993 UNICODE_SPLITLINES_METHODDEF
13994 UNICODE_STRIP_METHODDEF
13995 UNICODE_SWAPCASE_METHODDEF
13996 UNICODE_TRANSLATE_METHODDEF
13997 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013998 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13999 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090014000 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090014001 UNICODE_ISLOWER_METHODDEF
14002 UNICODE_ISUPPER_METHODDEF
14003 UNICODE_ISTITLE_METHODDEF
14004 UNICODE_ISSPACE_METHODDEF
14005 UNICODE_ISDECIMAL_METHODDEF
14006 UNICODE_ISDIGIT_METHODDEF
14007 UNICODE_ISNUMERIC_METHODDEF
14008 UNICODE_ISALPHA_METHODDEF
14009 UNICODE_ISALNUM_METHODDEF
14010 UNICODE_ISIDENTIFIER_METHODDEF
14011 UNICODE_ISPRINTABLE_METHODDEF
14012 UNICODE_ZFILL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +020014013 {"format", (PyCFunction)(void(*)(void)) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000014014 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090014015 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070014016 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090014017 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000014018#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000014019 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000014020 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000014021#endif
14022
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053014023 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000014024 {NULL, NULL}
14025};
14026
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014027static PyObject *
14028unicode_mod(PyObject *v, PyObject *w)
14029{
Brian Curtindfc80e32011-08-10 20:28:54 -050014030 if (!PyUnicode_Check(v))
14031 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000014032 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014033}
14034
14035static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014036 0, /*nb_add*/
14037 0, /*nb_subtract*/
14038 0, /*nb_multiply*/
14039 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014040};
14041
Guido van Rossumd57fd912000-03-10 22:53:23 +000014042static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 (lenfunc) unicode_length, /* sq_length */
14044 PyUnicode_Concat, /* sq_concat */
14045 (ssizeargfunc) unicode_repeat, /* sq_repeat */
14046 (ssizeargfunc) unicode_getitem, /* sq_item */
14047 0, /* sq_slice */
14048 0, /* sq_ass_item */
14049 0, /* sq_ass_slice */
14050 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014051};
14052
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014053static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014054unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014055{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014056 if (PyUnicode_READY(self) == -1)
14057 return NULL;
14058
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000014059 if (PyIndex_Check(item)) {
14060 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014061 if (i == -1 && PyErr_Occurred())
14062 return NULL;
14063 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014064 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014065 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014066 } else if (PySlice_Check(item)) {
Zackery Spytz14514d92019-05-17 01:13:03 -060014067 Py_ssize_t start, stop, step, slicelength, i;
14068 size_t cur;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014069 PyObject *result;
14070 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014071 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014072 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014073
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014074 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014075 return NULL;
14076 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014077 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14078 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014079
14080 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020014081 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014082 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010014083 slicelength == PyUnicode_GET_LENGTH(self)) {
14084 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000014085 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014086 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020014087 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014088 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014089 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014090 src_kind = PyUnicode_KIND(self);
14091 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020014092 if (!PyUnicode_IS_ASCII(self)) {
14093 kind_limit = kind_maxchar_limit(src_kind);
14094 max_char = 0;
14095 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14096 ch = PyUnicode_READ(src_kind, src_data, cur);
14097 if (ch > max_char) {
14098 max_char = ch;
14099 if (max_char >= kind_limit)
14100 break;
14101 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014102 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014103 }
Victor Stinner55c99112011-10-13 01:17:06 +020014104 else
14105 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014106 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014107 if (result == NULL)
14108 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014109 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014110 dest_data = PyUnicode_DATA(result);
14111
14112 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014113 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14114 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014115 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014116 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014117 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014118 } else {
14119 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14120 return NULL;
14121 }
14122}
14123
14124static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014125 (lenfunc)unicode_length, /* mp_length */
14126 (binaryfunc)unicode_subscript, /* mp_subscript */
14127 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014128};
14129
Guido van Rossumd57fd912000-03-10 22:53:23 +000014130
Guido van Rossumd57fd912000-03-10 22:53:23 +000014131/* Helpers for PyUnicode_Format() */
14132
Victor Stinnera47082312012-10-04 02:19:54 +020014133struct unicode_formatter_t {
14134 PyObject *args;
14135 int args_owned;
14136 Py_ssize_t arglen, argidx;
14137 PyObject *dict;
14138
14139 enum PyUnicode_Kind fmtkind;
14140 Py_ssize_t fmtcnt, fmtpos;
14141 void *fmtdata;
14142 PyObject *fmtstr;
14143
14144 _PyUnicodeWriter writer;
14145};
14146
14147struct unicode_format_arg_t {
14148 Py_UCS4 ch;
14149 int flags;
14150 Py_ssize_t width;
14151 int prec;
14152 int sign;
14153};
14154
Guido van Rossumd57fd912000-03-10 22:53:23 +000014155static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014156unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014157{
Victor Stinnera47082312012-10-04 02:19:54 +020014158 Py_ssize_t argidx = ctx->argidx;
14159
14160 if (argidx < ctx->arglen) {
14161 ctx->argidx++;
14162 if (ctx->arglen < 0)
14163 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014164 else
Victor Stinnera47082312012-10-04 02:19:54 +020014165 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014166 }
14167 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014168 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014169 return NULL;
14170}
14171
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014172/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014173
Victor Stinnera47082312012-10-04 02:19:54 +020014174/* Format a float into the writer if the writer is not NULL, or into *p_output
14175 otherwise.
14176
14177 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014178static int
Victor Stinnera47082312012-10-04 02:19:54 +020014179formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14180 PyObject **p_output,
14181 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014182{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014183 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014184 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014185 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014186 int prec;
14187 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014188
Guido van Rossumd57fd912000-03-10 22:53:23 +000014189 x = PyFloat_AsDouble(v);
14190 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014191 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014192
Victor Stinnera47082312012-10-04 02:19:54 +020014193 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014194 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014195 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014196
Victor Stinnera47082312012-10-04 02:19:54 +020014197 if (arg->flags & F_ALT)
14198 dtoa_flags = Py_DTSF_ALT;
14199 else
14200 dtoa_flags = 0;
14201 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014202 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014203 return -1;
14204 len = strlen(p);
14205 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014206 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014207 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014208 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014209 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014210 }
14211 else
14212 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014213 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014214 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014215}
14216
Victor Stinnerd0880d52012-04-27 23:40:13 +020014217/* formatlong() emulates the format codes d, u, o, x and X, and
14218 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14219 * Python's regular ints.
14220 * Return value: a new PyUnicodeObject*, or NULL if error.
14221 * The output string is of the form
14222 * "-"? ("0x" | "0X")? digit+
14223 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14224 * set in flags. The case of hex digits will be correct,
14225 * There will be at least prec digits, zero-filled on the left if
14226 * necessary to get that many.
14227 * val object to be converted
14228 * flags bitmask of format flags; only F_ALT is looked at
14229 * prec minimum number of digits; 0-fill on left if needed
14230 * type a character in [duoxX]; u acts the same as d
14231 *
14232 * CAUTION: o, x and X conversions on regular ints can never
14233 * produce a '-' sign, but can for Python's unbounded ints.
14234 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014235PyObject *
14236_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014237{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014238 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014239 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014240 Py_ssize_t i;
14241 int sign; /* 1 if '-', else 0 */
14242 int len; /* number of characters */
14243 Py_ssize_t llen;
14244 int numdigits; /* len == numnondigits + numdigits */
14245 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014246
Victor Stinnerd0880d52012-04-27 23:40:13 +020014247 /* Avoid exceeding SSIZE_T_MAX */
14248 if (prec > INT_MAX-3) {
14249 PyErr_SetString(PyExc_OverflowError,
14250 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014251 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014252 }
14253
14254 assert(PyLong_Check(val));
14255
14256 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014257 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014258 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014259 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014260 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014261 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014262 /* int and int subclasses should print numerically when a numeric */
14263 /* format code is used (see issue18780) */
14264 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014265 break;
14266 case 'o':
14267 numnondigits = 2;
14268 result = PyNumber_ToBase(val, 8);
14269 break;
14270 case 'x':
14271 case 'X':
14272 numnondigits = 2;
14273 result = PyNumber_ToBase(val, 16);
14274 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014275 }
14276 if (!result)
14277 return NULL;
14278
14279 assert(unicode_modifiable(result));
14280 assert(PyUnicode_IS_READY(result));
14281 assert(PyUnicode_IS_ASCII(result));
14282
14283 /* To modify the string in-place, there can only be one reference. */
14284 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014285 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014286 PyErr_BadInternalCall();
14287 return NULL;
14288 }
14289 buf = PyUnicode_DATA(result);
14290 llen = PyUnicode_GET_LENGTH(result);
14291 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014292 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014293 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014294 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014295 return NULL;
14296 }
14297 len = (int)llen;
14298 sign = buf[0] == '-';
14299 numnondigits += sign;
14300 numdigits = len - numnondigits;
14301 assert(numdigits > 0);
14302
14303 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014304 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014305 (type == 'o' || type == 'x' || type == 'X'))) {
14306 assert(buf[sign] == '0');
14307 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14308 buf[sign+1] == 'o');
14309 numnondigits -= 2;
14310 buf += 2;
14311 len -= 2;
14312 if (sign)
14313 buf[0] = '-';
14314 assert(len == numnondigits + numdigits);
14315 assert(numdigits > 0);
14316 }
14317
14318 /* Fill with leading zeroes to meet minimum width. */
14319 if (prec > numdigits) {
14320 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14321 numnondigits + prec);
14322 char *b1;
14323 if (!r1) {
14324 Py_DECREF(result);
14325 return NULL;
14326 }
14327 b1 = PyBytes_AS_STRING(r1);
14328 for (i = 0; i < numnondigits; ++i)
14329 *b1++ = *buf++;
14330 for (i = 0; i < prec - numdigits; i++)
14331 *b1++ = '0';
14332 for (i = 0; i < numdigits; i++)
14333 *b1++ = *buf++;
14334 *b1 = '\0';
14335 Py_DECREF(result);
14336 result = r1;
14337 buf = PyBytes_AS_STRING(result);
14338 len = numnondigits + prec;
14339 }
14340
14341 /* Fix up case for hex conversions. */
14342 if (type == 'X') {
14343 /* Need to convert all lower case letters to upper case.
14344 and need to convert 0x to 0X (and -0x to -0X). */
14345 for (i = 0; i < len; i++)
14346 if (buf[i] >= 'a' && buf[i] <= 'x')
14347 buf[i] -= 'a'-'A';
14348 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014349 if (!PyUnicode_Check(result)
14350 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014351 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014352 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014353 Py_DECREF(result);
14354 result = unicode;
14355 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014356 else if (len != PyUnicode_GET_LENGTH(result)) {
14357 if (PyUnicode_Resize(&result, len) < 0)
14358 Py_CLEAR(result);
14359 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014360 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014361}
14362
Ethan Furmandf3ed242014-01-05 06:50:30 -080014363/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014364 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014365 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014366 * -1 and raise an exception on error */
14367static int
Victor Stinnera47082312012-10-04 02:19:54 +020014368mainformatlong(PyObject *v,
14369 struct unicode_format_arg_t *arg,
14370 PyObject **p_output,
14371 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014372{
14373 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014374 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014375
14376 if (!PyNumber_Check(v))
14377 goto wrongtype;
14378
Ethan Furman9ab74802014-03-21 06:38:46 -070014379 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014380 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014381 if (type == 'o' || type == 'x' || type == 'X') {
14382 iobj = PyNumber_Index(v);
14383 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014384 if (PyErr_ExceptionMatches(PyExc_TypeError))
14385 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014386 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014387 }
14388 }
14389 else {
14390 iobj = PyNumber_Long(v);
14391 if (iobj == NULL ) {
14392 if (PyErr_ExceptionMatches(PyExc_TypeError))
14393 goto wrongtype;
14394 return -1;
14395 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014396 }
14397 assert(PyLong_Check(iobj));
14398 }
14399 else {
14400 iobj = v;
14401 Py_INCREF(iobj);
14402 }
14403
14404 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014405 && arg->width == -1 && arg->prec == -1
14406 && !(arg->flags & (F_SIGN | F_BLANK))
14407 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014408 {
14409 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014410 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014411 int base;
14412
Victor Stinnera47082312012-10-04 02:19:54 +020014413 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014414 {
14415 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014416 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014417 case 'd':
14418 case 'i':
14419 case 'u':
14420 base = 10;
14421 break;
14422 case 'o':
14423 base = 8;
14424 break;
14425 case 'x':
14426 case 'X':
14427 base = 16;
14428 break;
14429 }
14430
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014431 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14432 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014433 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014434 }
14435 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014436 return 1;
14437 }
14438
Ethan Furmanb95b5612015-01-23 20:05:18 -080014439 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014440 Py_DECREF(iobj);
14441 if (res == NULL)
14442 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014443 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014444 return 0;
14445
14446wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014447 switch(type)
14448 {
14449 case 'o':
14450 case 'x':
14451 case 'X':
14452 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014453 "%%%c format: an integer is required, "
14454 "not %.200s",
14455 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014456 break;
14457 default:
14458 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014459 "%%%c format: a number is required, "
14460 "not %.200s",
14461 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014462 break;
14463 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014464 return -1;
14465}
14466
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014467static Py_UCS4
14468formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014469{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014470 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014471 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014472 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014473 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014474 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014475 goto onError;
14476 }
14477 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014478 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014479 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014480 /* make sure number is a type of integer */
14481 if (!PyLong_Check(v)) {
14482 iobj = PyNumber_Index(v);
14483 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014484 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014485 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014486 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014487 Py_DECREF(iobj);
14488 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014489 else {
14490 x = PyLong_AsLong(v);
14491 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014492 if (x == -1 && PyErr_Occurred())
14493 goto onError;
14494
Victor Stinner8faf8212011-12-08 22:14:11 +010014495 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014496 PyErr_SetString(PyExc_OverflowError,
14497 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014498 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014499 }
14500
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014501 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014502 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014503
Benjamin Peterson29060642009-01-31 22:14:21 +000014504 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014505 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014506 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014507 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014508}
14509
Victor Stinnera47082312012-10-04 02:19:54 +020014510/* Parse options of an argument: flags, width, precision.
14511 Handle also "%(name)" syntax.
14512
14513 Return 0 if the argument has been formatted into arg->str.
14514 Return 1 if the argument has been written into ctx->writer,
14515 Raise an exception and return -1 on error. */
14516static int
14517unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14518 struct unicode_format_arg_t *arg)
14519{
14520#define FORMAT_READ(ctx) \
14521 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14522
14523 PyObject *v;
14524
Victor Stinnera47082312012-10-04 02:19:54 +020014525 if (arg->ch == '(') {
14526 /* Get argument value from a dictionary. Example: "%(name)s". */
14527 Py_ssize_t keystart;
14528 Py_ssize_t keylen;
14529 PyObject *key;
14530 int pcount = 1;
14531
14532 if (ctx->dict == NULL) {
14533 PyErr_SetString(PyExc_TypeError,
14534 "format requires a mapping");
14535 return -1;
14536 }
14537 ++ctx->fmtpos;
14538 --ctx->fmtcnt;
14539 keystart = ctx->fmtpos;
14540 /* Skip over balanced parentheses */
14541 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14542 arg->ch = FORMAT_READ(ctx);
14543 if (arg->ch == ')')
14544 --pcount;
14545 else if (arg->ch == '(')
14546 ++pcount;
14547 ctx->fmtpos++;
14548 }
14549 keylen = ctx->fmtpos - keystart - 1;
14550 if (ctx->fmtcnt < 0 || pcount > 0) {
14551 PyErr_SetString(PyExc_ValueError,
14552 "incomplete format key");
14553 return -1;
14554 }
14555 key = PyUnicode_Substring(ctx->fmtstr,
14556 keystart, keystart + keylen);
14557 if (key == NULL)
14558 return -1;
14559 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014560 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014561 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014562 }
14563 ctx->args = PyObject_GetItem(ctx->dict, key);
14564 Py_DECREF(key);
14565 if (ctx->args == NULL)
14566 return -1;
14567 ctx->args_owned = 1;
14568 ctx->arglen = -1;
14569 ctx->argidx = -2;
14570 }
14571
14572 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014573 while (--ctx->fmtcnt >= 0) {
14574 arg->ch = FORMAT_READ(ctx);
14575 ctx->fmtpos++;
14576 switch (arg->ch) {
14577 case '-': arg->flags |= F_LJUST; continue;
14578 case '+': arg->flags |= F_SIGN; continue;
14579 case ' ': arg->flags |= F_BLANK; continue;
14580 case '#': arg->flags |= F_ALT; continue;
14581 case '0': arg->flags |= F_ZERO; continue;
14582 }
14583 break;
14584 }
14585
14586 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014587 if (arg->ch == '*') {
14588 v = unicode_format_getnextarg(ctx);
14589 if (v == NULL)
14590 return -1;
14591 if (!PyLong_Check(v)) {
14592 PyErr_SetString(PyExc_TypeError,
14593 "* wants int");
14594 return -1;
14595 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014596 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014597 if (arg->width == -1 && PyErr_Occurred())
14598 return -1;
14599 if (arg->width < 0) {
14600 arg->flags |= F_LJUST;
14601 arg->width = -arg->width;
14602 }
14603 if (--ctx->fmtcnt >= 0) {
14604 arg->ch = FORMAT_READ(ctx);
14605 ctx->fmtpos++;
14606 }
14607 }
14608 else if (arg->ch >= '0' && arg->ch <= '9') {
14609 arg->width = arg->ch - '0';
14610 while (--ctx->fmtcnt >= 0) {
14611 arg->ch = FORMAT_READ(ctx);
14612 ctx->fmtpos++;
14613 if (arg->ch < '0' || arg->ch > '9')
14614 break;
14615 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14616 mixing signed and unsigned comparison. Since arg->ch is between
14617 '0' and '9', casting to int is safe. */
14618 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14619 PyErr_SetString(PyExc_ValueError,
14620 "width too big");
14621 return -1;
14622 }
14623 arg->width = arg->width*10 + (arg->ch - '0');
14624 }
14625 }
14626
14627 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014628 if (arg->ch == '.') {
14629 arg->prec = 0;
14630 if (--ctx->fmtcnt >= 0) {
14631 arg->ch = FORMAT_READ(ctx);
14632 ctx->fmtpos++;
14633 }
14634 if (arg->ch == '*') {
14635 v = unicode_format_getnextarg(ctx);
14636 if (v == NULL)
14637 return -1;
14638 if (!PyLong_Check(v)) {
14639 PyErr_SetString(PyExc_TypeError,
14640 "* wants int");
14641 return -1;
14642 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014643 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014644 if (arg->prec == -1 && PyErr_Occurred())
14645 return -1;
14646 if (arg->prec < 0)
14647 arg->prec = 0;
14648 if (--ctx->fmtcnt >= 0) {
14649 arg->ch = FORMAT_READ(ctx);
14650 ctx->fmtpos++;
14651 }
14652 }
14653 else if (arg->ch >= '0' && arg->ch <= '9') {
14654 arg->prec = arg->ch - '0';
14655 while (--ctx->fmtcnt >= 0) {
14656 arg->ch = FORMAT_READ(ctx);
14657 ctx->fmtpos++;
14658 if (arg->ch < '0' || arg->ch > '9')
14659 break;
14660 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14661 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014662 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014663 return -1;
14664 }
14665 arg->prec = arg->prec*10 + (arg->ch - '0');
14666 }
14667 }
14668 }
14669
14670 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14671 if (ctx->fmtcnt >= 0) {
14672 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14673 if (--ctx->fmtcnt >= 0) {
14674 arg->ch = FORMAT_READ(ctx);
14675 ctx->fmtpos++;
14676 }
14677 }
14678 }
14679 if (ctx->fmtcnt < 0) {
14680 PyErr_SetString(PyExc_ValueError,
14681 "incomplete format");
14682 return -1;
14683 }
14684 return 0;
14685
14686#undef FORMAT_READ
14687}
14688
14689/* Format one argument. Supported conversion specifiers:
14690
14691 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014692 - "i", "d", "u": int or float
14693 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014694 - "e", "E", "f", "F", "g", "G": float
14695 - "c": int or str (1 character)
14696
Victor Stinner8dbd4212012-12-04 09:30:24 +010014697 When possible, the output is written directly into the Unicode writer
14698 (ctx->writer). A string is created when padding is required.
14699
Victor Stinnera47082312012-10-04 02:19:54 +020014700 Return 0 if the argument has been formatted into *p_str,
14701 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014702 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014703static int
14704unicode_format_arg_format(struct unicode_formatter_t *ctx,
14705 struct unicode_format_arg_t *arg,
14706 PyObject **p_str)
14707{
14708 PyObject *v;
14709 _PyUnicodeWriter *writer = &ctx->writer;
14710
14711 if (ctx->fmtcnt == 0)
14712 ctx->writer.overallocate = 0;
14713
Victor Stinnera47082312012-10-04 02:19:54 +020014714 v = unicode_format_getnextarg(ctx);
14715 if (v == NULL)
14716 return -1;
14717
Victor Stinnera47082312012-10-04 02:19:54 +020014718
14719 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014720 case 's':
14721 case 'r':
14722 case 'a':
14723 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14724 /* Fast path */
14725 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14726 return -1;
14727 return 1;
14728 }
14729
14730 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14731 *p_str = v;
14732 Py_INCREF(*p_str);
14733 }
14734 else {
14735 if (arg->ch == 's')
14736 *p_str = PyObject_Str(v);
14737 else if (arg->ch == 'r')
14738 *p_str = PyObject_Repr(v);
14739 else
14740 *p_str = PyObject_ASCII(v);
14741 }
14742 break;
14743
14744 case 'i':
14745 case 'd':
14746 case 'u':
14747 case 'o':
14748 case 'x':
14749 case 'X':
14750 {
14751 int ret = mainformatlong(v, arg, p_str, writer);
14752 if (ret != 0)
14753 return ret;
14754 arg->sign = 1;
14755 break;
14756 }
14757
14758 case 'e':
14759 case 'E':
14760 case 'f':
14761 case 'F':
14762 case 'g':
14763 case 'G':
14764 if (arg->width == -1 && arg->prec == -1
14765 && !(arg->flags & (F_SIGN | F_BLANK)))
14766 {
14767 /* Fast path */
14768 if (formatfloat(v, arg, NULL, writer) == -1)
14769 return -1;
14770 return 1;
14771 }
14772
14773 arg->sign = 1;
14774 if (formatfloat(v, arg, p_str, NULL) == -1)
14775 return -1;
14776 break;
14777
14778 case 'c':
14779 {
14780 Py_UCS4 ch = formatchar(v);
14781 if (ch == (Py_UCS4) -1)
14782 return -1;
14783 if (arg->width == -1 && arg->prec == -1) {
14784 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014785 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014786 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014787 return 1;
14788 }
14789 *p_str = PyUnicode_FromOrdinal(ch);
14790 break;
14791 }
14792
14793 default:
14794 PyErr_Format(PyExc_ValueError,
14795 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014796 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014797 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14798 (int)arg->ch,
14799 ctx->fmtpos - 1);
14800 return -1;
14801 }
14802 if (*p_str == NULL)
14803 return -1;
14804 assert (PyUnicode_Check(*p_str));
14805 return 0;
14806}
14807
14808static int
14809unicode_format_arg_output(struct unicode_formatter_t *ctx,
14810 struct unicode_format_arg_t *arg,
14811 PyObject *str)
14812{
14813 Py_ssize_t len;
14814 enum PyUnicode_Kind kind;
14815 void *pbuf;
14816 Py_ssize_t pindex;
14817 Py_UCS4 signchar;
14818 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014819 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014820 Py_ssize_t sublen;
14821 _PyUnicodeWriter *writer = &ctx->writer;
14822 Py_UCS4 fill;
14823
14824 fill = ' ';
14825 if (arg->sign && arg->flags & F_ZERO)
14826 fill = '0';
14827
14828 if (PyUnicode_READY(str) == -1)
14829 return -1;
14830
14831 len = PyUnicode_GET_LENGTH(str);
14832 if ((arg->width == -1 || arg->width <= len)
14833 && (arg->prec == -1 || arg->prec >= len)
14834 && !(arg->flags & (F_SIGN | F_BLANK)))
14835 {
14836 /* Fast path */
14837 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14838 return -1;
14839 return 0;
14840 }
14841
14842 /* Truncate the string for "s", "r" and "a" formats
14843 if the precision is set */
14844 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14845 if (arg->prec >= 0 && len > arg->prec)
14846 len = arg->prec;
14847 }
14848
14849 /* Adjust sign and width */
14850 kind = PyUnicode_KIND(str);
14851 pbuf = PyUnicode_DATA(str);
14852 pindex = 0;
14853 signchar = '\0';
14854 if (arg->sign) {
14855 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14856 if (ch == '-' || ch == '+') {
14857 signchar = ch;
14858 len--;
14859 pindex++;
14860 }
14861 else if (arg->flags & F_SIGN)
14862 signchar = '+';
14863 else if (arg->flags & F_BLANK)
14864 signchar = ' ';
14865 else
14866 arg->sign = 0;
14867 }
14868 if (arg->width < len)
14869 arg->width = len;
14870
14871 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014872 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014873 if (!(arg->flags & F_LJUST)) {
14874 if (arg->sign) {
14875 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014876 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014877 }
14878 else {
14879 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014880 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014881 }
14882 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014883 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14884 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014885 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014886 }
14887
Victor Stinnera47082312012-10-04 02:19:54 +020014888 buflen = arg->width;
14889 if (arg->sign && len == arg->width)
14890 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014891 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014892 return -1;
14893
14894 /* Write the sign if needed */
14895 if (arg->sign) {
14896 if (fill != ' ') {
14897 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14898 writer->pos += 1;
14899 }
14900 if (arg->width > len)
14901 arg->width--;
14902 }
14903
14904 /* Write the numeric prefix for "x", "X" and "o" formats
14905 if the alternate form is used.
14906 For example, write "0x" for the "%#x" format. */
14907 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14908 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14909 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14910 if (fill != ' ') {
14911 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14912 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14913 writer->pos += 2;
14914 pindex += 2;
14915 }
14916 arg->width -= 2;
14917 if (arg->width < 0)
14918 arg->width = 0;
14919 len -= 2;
14920 }
14921
14922 /* Pad left with the fill character if needed */
14923 if (arg->width > len && !(arg->flags & F_LJUST)) {
14924 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014925 unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014926 writer->pos += sublen;
14927 arg->width = len;
14928 }
14929
14930 /* If padding with spaces: write sign if needed and/or numeric prefix if
14931 the alternate form is used */
14932 if (fill == ' ') {
14933 if (arg->sign) {
14934 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14935 writer->pos += 1;
14936 }
14937 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14938 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14939 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14940 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14941 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14942 writer->pos += 2;
14943 pindex += 2;
14944 }
14945 }
14946
14947 /* Write characters */
14948 if (len) {
14949 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14950 str, pindex, len);
14951 writer->pos += len;
14952 }
14953
14954 /* Pad right with the fill character if needed */
14955 if (arg->width > len) {
14956 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014957 unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014958 writer->pos += sublen;
14959 }
14960 return 0;
14961}
14962
14963/* Helper of PyUnicode_Format(): format one arg.
14964 Return 0 on success, raise an exception and return -1 on error. */
14965static int
14966unicode_format_arg(struct unicode_formatter_t *ctx)
14967{
14968 struct unicode_format_arg_t arg;
14969 PyObject *str;
14970 int ret;
14971
Victor Stinner8dbd4212012-12-04 09:30:24 +010014972 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014973 if (arg.ch == '%') {
14974 ctx->fmtpos++;
14975 ctx->fmtcnt--;
14976 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14977 return -1;
14978 return 0;
14979 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014980 arg.flags = 0;
14981 arg.width = -1;
14982 arg.prec = -1;
14983 arg.sign = 0;
14984 str = NULL;
14985
Victor Stinnera47082312012-10-04 02:19:54 +020014986 ret = unicode_format_arg_parse(ctx, &arg);
14987 if (ret == -1)
14988 return -1;
14989
14990 ret = unicode_format_arg_format(ctx, &arg, &str);
14991 if (ret == -1)
14992 return -1;
14993
14994 if (ret != 1) {
14995 ret = unicode_format_arg_output(ctx, &arg, str);
14996 Py_DECREF(str);
14997 if (ret == -1)
14998 return -1;
14999 }
15000
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020015001 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020015002 PyErr_SetString(PyExc_TypeError,
15003 "not all arguments converted during string formatting");
15004 return -1;
15005 }
15006 return 0;
15007}
15008
Alexander Belopolsky40018472011-02-26 01:02:56 +000015009PyObject *
15010PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015011{
Victor Stinnera47082312012-10-04 02:19:54 +020015012 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000015013
Guido van Rossumd57fd912000-03-10 22:53:23 +000015014 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015015 PyErr_BadInternalCall();
15016 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015017 }
Victor Stinnera47082312012-10-04 02:19:54 +020015018
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030015019 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015020 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030015021
15022 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020015023 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
15024 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
15025 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
15026 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020015027
Victor Stinner8f674cc2013-04-17 23:02:17 +020015028 _PyUnicodeWriter_Init(&ctx.writer);
15029 ctx.writer.min_length = ctx.fmtcnt + 100;
15030 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020015031
Guido van Rossumd57fd912000-03-10 22:53:23 +000015032 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020015033 ctx.arglen = PyTuple_Size(args);
15034 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015035 }
15036 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015037 ctx.arglen = -1;
15038 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015039 }
Victor Stinnera47082312012-10-04 02:19:54 +020015040 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040015041 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020015042 ctx.dict = args;
15043 else
15044 ctx.dict = NULL;
15045 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015046
Victor Stinnera47082312012-10-04 02:19:54 +020015047 while (--ctx.fmtcnt >= 0) {
15048 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020015049 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020015050
15051 nonfmtpos = ctx.fmtpos++;
15052 while (ctx.fmtcnt >= 0 &&
15053 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
15054 ctx.fmtpos++;
15055 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015056 }
Victor Stinnera47082312012-10-04 02:19:54 +020015057 if (ctx.fmtcnt < 0) {
15058 ctx.fmtpos--;
15059 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020015060 }
Victor Stinneree4544c2012-05-09 22:24:08 +020015061
Victor Stinnercfc4c132013-04-03 01:48:39 +020015062 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
15063 nonfmtpos, ctx.fmtpos) < 0)
15064 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015065 }
15066 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015067 ctx.fmtpos++;
15068 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000015069 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020015070 }
15071 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020015072
Victor Stinnera47082312012-10-04 02:19:54 +020015073 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015074 PyErr_SetString(PyExc_TypeError,
15075 "not all arguments converted during string formatting");
15076 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015077 }
15078
Victor Stinnera47082312012-10-04 02:19:54 +020015079 if (ctx.args_owned) {
15080 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015081 }
Victor Stinnera47082312012-10-04 02:19:54 +020015082 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015083
Benjamin Peterson29060642009-01-31 22:14:21 +000015084 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020015085 _PyUnicodeWriter_Dealloc(&ctx.writer);
15086 if (ctx.args_owned) {
15087 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015088 }
15089 return NULL;
15090}
15091
Jeremy Hylton938ace62002-07-17 16:30:39 +000015092static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000015093unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
15094
Tim Peters6d6c1a32001-08-02 04:15:00 +000015095static PyObject *
15096unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15097{
Benjamin Peterson29060642009-01-31 22:14:21 +000015098 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015099 static char *kwlist[] = {"object", "encoding", "errors", 0};
15100 char *encoding = NULL;
15101 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015102
Benjamin Peterson14339b62009-01-31 16:36:08 +000015103 if (type != &PyUnicode_Type)
15104 return unicode_subtype_new(type, args, kwds);
15105 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015106 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015107 return NULL;
15108 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015109 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015110 if (encoding == NULL && errors == NULL)
15111 return PyObject_Str(x);
15112 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015113 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015114}
15115
Guido van Rossume023fe02001-08-30 03:12:59 +000015116static PyObject *
15117unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15118{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015119 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015120 Py_ssize_t length, char_size;
15121 int share_wstr, share_utf8;
15122 unsigned int kind;
15123 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015124
Benjamin Peterson14339b62009-01-31 16:36:08 +000015125 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015126
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015127 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015128 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015129 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015130 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015131 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015132 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015133 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015134 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015135
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015136 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015137 if (self == NULL) {
15138 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015139 return NULL;
15140 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015141 kind = PyUnicode_KIND(unicode);
15142 length = PyUnicode_GET_LENGTH(unicode);
15143
15144 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015145#ifdef Py_DEBUG
15146 _PyUnicode_HASH(self) = -1;
15147#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015148 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015149#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015150 _PyUnicode_STATE(self).interned = 0;
15151 _PyUnicode_STATE(self).kind = kind;
15152 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015153 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015154 _PyUnicode_STATE(self).ready = 1;
15155 _PyUnicode_WSTR(self) = NULL;
15156 _PyUnicode_UTF8_LENGTH(self) = 0;
15157 _PyUnicode_UTF8(self) = NULL;
15158 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015159 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015160
15161 share_utf8 = 0;
15162 share_wstr = 0;
15163 if (kind == PyUnicode_1BYTE_KIND) {
15164 char_size = 1;
15165 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15166 share_utf8 = 1;
15167 }
15168 else if (kind == PyUnicode_2BYTE_KIND) {
15169 char_size = 2;
15170 if (sizeof(wchar_t) == 2)
15171 share_wstr = 1;
15172 }
15173 else {
15174 assert(kind == PyUnicode_4BYTE_KIND);
15175 char_size = 4;
15176 if (sizeof(wchar_t) == 4)
15177 share_wstr = 1;
15178 }
15179
15180 /* Ensure we won't overflow the length. */
15181 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15182 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015183 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015184 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015185 data = PyObject_MALLOC((length + 1) * char_size);
15186 if (data == NULL) {
15187 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015188 goto onError;
15189 }
15190
Victor Stinnerc3c74152011-10-02 20:39:55 +020015191 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015192 if (share_utf8) {
15193 _PyUnicode_UTF8_LENGTH(self) = length;
15194 _PyUnicode_UTF8(self) = data;
15195 }
15196 if (share_wstr) {
15197 _PyUnicode_WSTR_LENGTH(self) = length;
15198 _PyUnicode_WSTR(self) = (wchar_t *)data;
15199 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015200
Christian Heimesf051e432016-09-13 20:22:02 +020015201 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015202 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015203 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015204#ifdef Py_DEBUG
15205 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15206#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015207 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015208 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015209
15210onError:
15211 Py_DECREF(unicode);
15212 Py_DECREF(self);
15213 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015214}
15215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015216PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015217"str(object='') -> str\n\
15218str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015219\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015220Create a new string object from the given object. If encoding or\n\
15221errors is specified, then the object must expose a data buffer\n\
15222that will be decoded using the given encoding and error handler.\n\
15223Otherwise, returns the result of object.__str__() (if defined)\n\
15224or repr(object).\n\
15225encoding defaults to sys.getdefaultencoding().\n\
15226errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015227
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015228static PyObject *unicode_iter(PyObject *seq);
15229
Guido van Rossumd57fd912000-03-10 22:53:23 +000015230PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015231 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015232 "str", /* tp_name */
15233 sizeof(PyUnicodeObject), /* tp_basicsize */
15234 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015235 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015236 (destructor)unicode_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020015237 0, /* tp_vectorcall_offset */
Bupfc93bd42018-06-19 03:59:55 -050015238 0, /* tp_getattr */
15239 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020015240 0, /* tp_as_async */
Bupfc93bd42018-06-19 03:59:55 -050015241 unicode_repr, /* tp_repr */
15242 &unicode_as_number, /* tp_as_number */
15243 &unicode_as_sequence, /* tp_as_sequence */
15244 &unicode_as_mapping, /* tp_as_mapping */
15245 (hashfunc) unicode_hash, /* tp_hash*/
15246 0, /* tp_call*/
15247 (reprfunc) unicode_str, /* tp_str */
15248 PyObject_GenericGetAttr, /* tp_getattro */
15249 0, /* tp_setattro */
15250 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015251 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015252 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15253 unicode_doc, /* tp_doc */
15254 0, /* tp_traverse */
15255 0, /* tp_clear */
15256 PyUnicode_RichCompare, /* tp_richcompare */
15257 0, /* tp_weaklistoffset */
15258 unicode_iter, /* tp_iter */
15259 0, /* tp_iternext */
15260 unicode_methods, /* tp_methods */
15261 0, /* tp_members */
15262 0, /* tp_getset */
15263 &PyBaseObject_Type, /* tp_base */
15264 0, /* tp_dict */
15265 0, /* tp_descr_get */
15266 0, /* tp_descr_set */
15267 0, /* tp_dictoffset */
15268 0, /* tp_init */
15269 0, /* tp_alloc */
15270 unicode_new, /* tp_new */
15271 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015272};
15273
15274/* Initialize the Unicode implementation */
15275
Victor Stinner331a6a52019-05-27 16:39:22 +020015276PyStatus
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015277_PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015278{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015279 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015280 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015281 0x000A, /* LINE FEED */
15282 0x000D, /* CARRIAGE RETURN */
15283 0x001C, /* FILE SEPARATOR */
15284 0x001D, /* GROUP SEPARATOR */
15285 0x001E, /* RECORD SEPARATOR */
15286 0x0085, /* NEXT LINE */
15287 0x2028, /* LINE SEPARATOR */
15288 0x2029, /* PARAGRAPH SEPARATOR */
15289 };
15290
Fred Drakee4315f52000-05-09 19:53:39 +000015291 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015292 _Py_INCREF_UNICODE_EMPTY();
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015293 if (!unicode_empty) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015294 return _PyStatus_ERR("Can't create empty string");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015295 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020015296 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015297
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015298 if (PyType_Ready(&PyUnicode_Type) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015299 return _PyStatus_ERR("Can't initialize unicode type");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015300 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015301
15302 /* initialize the linebreak bloom filter */
15303 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015304 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015305 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015306
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015307 if (PyType_Ready(&EncodingMapType) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015308 return _PyStatus_ERR("Can't initialize encoding map type");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015309 }
15310 if (PyType_Ready(&PyFieldNameIter_Type) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015311 return _PyStatus_ERR("Can't initialize field name iterator type");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015312 }
15313 if (PyType_Ready(&PyFormatterIter_Type) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015314 return _PyStatus_ERR("Can't initialize formatter iter type");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015315 }
Victor Stinner331a6a52019-05-27 16:39:22 +020015316 return _PyStatus_OK();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015317}
15318
15319/* Finalize the Unicode implementation */
15320
Christian Heimesa156e092008-02-16 07:38:31 +000015321int
15322PyUnicode_ClearFreeList(void)
15323{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015324 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015325}
15326
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015327
Walter Dörwald16807132007-05-25 13:52:07 +000015328void
15329PyUnicode_InternInPlace(PyObject **p)
15330{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015331 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015332 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015333#ifdef Py_DEBUG
15334 assert(s != NULL);
15335 assert(_PyUnicode_CHECK(s));
15336#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015337 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015338 return;
15339#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015340 /* If it's a subclass, we don't really know what putting
15341 it in the interned dict might do. */
15342 if (!PyUnicode_CheckExact(s))
15343 return;
15344 if (PyUnicode_CHECK_INTERNED(s))
15345 return;
15346 if (interned == NULL) {
15347 interned = PyDict_New();
15348 if (interned == NULL) {
15349 PyErr_Clear(); /* Don't leave an exception */
15350 return;
15351 }
15352 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015353 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015354 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015355 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015356 if (t == NULL) {
15357 PyErr_Clear();
15358 return;
15359 }
15360 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015361 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015362 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015363 return;
15364 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015365 /* The two references in interned are not counted by refcnt.
15366 The deallocator will take care of this */
15367 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015368 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015369}
15370
15371void
15372PyUnicode_InternImmortal(PyObject **p)
15373{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015374 PyUnicode_InternInPlace(p);
15375 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015376 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015377 Py_INCREF(*p);
15378 }
Walter Dörwald16807132007-05-25 13:52:07 +000015379}
15380
15381PyObject *
15382PyUnicode_InternFromString(const char *cp)
15383{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015384 PyObject *s = PyUnicode_FromString(cp);
15385 if (s == NULL)
15386 return NULL;
15387 PyUnicode_InternInPlace(&s);
15388 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015389}
15390
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015391
15392#if defined(WITH_VALGRIND) || defined(__INSURE__)
15393static void
15394unicode_release_interned(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015395{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015396 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015397 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015398 Py_ssize_t i, n;
15399 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015400
Benjamin Peterson14339b62009-01-31 16:36:08 +000015401 if (interned == NULL || !PyDict_Check(interned))
15402 return;
15403 keys = PyDict_Keys(interned);
15404 if (keys == NULL || !PyList_Check(keys)) {
15405 PyErr_Clear();
15406 return;
15407 }
Walter Dörwald16807132007-05-25 13:52:07 +000015408
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015409 /* Since unicode_release_interned() is intended to help a leak
Benjamin Peterson14339b62009-01-31 16:36:08 +000015410 detector, interned unicode strings are not forcibly deallocated;
15411 rather, we give them their stolen references back, and then clear
15412 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015413
Benjamin Peterson14339b62009-01-31 16:36:08 +000015414 n = PyList_GET_SIZE(keys);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015415#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015416 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015417 n);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015418#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015419 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015420 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015421 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015422 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015423 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015424 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015425 case SSTATE_NOT_INTERNED:
15426 /* XXX Shouldn't happen */
15427 break;
15428 case SSTATE_INTERNED_IMMORTAL:
15429 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015430 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015431 break;
15432 case SSTATE_INTERNED_MORTAL:
15433 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015434 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015435 break;
15436 default:
15437 Py_FatalError("Inconsistent interned string state.");
15438 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015439 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015440 }
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015441#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015442 fprintf(stderr, "total size of all interned strings: "
15443 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15444 "mortal/immortal\n", mortal_size, immortal_size);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015445#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015446 Py_DECREF(keys);
15447 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015448 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015449}
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015450#endif
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015451
15452
15453/********************* Unicode Iterator **************************/
15454
15455typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015456 PyObject_HEAD
15457 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015458 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015459} unicodeiterobject;
15460
15461static void
15462unicodeiter_dealloc(unicodeiterobject *it)
15463{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015464 _PyObject_GC_UNTRACK(it);
15465 Py_XDECREF(it->it_seq);
15466 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015467}
15468
15469static int
15470unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15471{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015472 Py_VISIT(it->it_seq);
15473 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015474}
15475
15476static PyObject *
15477unicodeiter_next(unicodeiterobject *it)
15478{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015479 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015480
Benjamin Peterson14339b62009-01-31 16:36:08 +000015481 assert(it != NULL);
15482 seq = it->it_seq;
15483 if (seq == NULL)
15484 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015485 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015486
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015487 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15488 int kind = PyUnicode_KIND(seq);
15489 void *data = PyUnicode_DATA(seq);
15490 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15491 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015492 if (item != NULL)
15493 ++it->it_index;
15494 return item;
15495 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015496
Benjamin Peterson14339b62009-01-31 16:36:08 +000015497 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015498 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015499 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015500}
15501
15502static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015503unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015504{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015505 Py_ssize_t len = 0;
15506 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015507 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015508 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015509}
15510
15511PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15512
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015513static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015514unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015515{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015516 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015517 if (it->it_seq != NULL) {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015518 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015519 it->it_seq, it->it_index);
15520 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015521 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015522 if (u == NULL)
15523 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015524 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015525 }
15526}
15527
15528PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15529
15530static PyObject *
15531unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15532{
15533 Py_ssize_t index = PyLong_AsSsize_t(state);
15534 if (index == -1 && PyErr_Occurred())
15535 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015536 if (it->it_seq != NULL) {
15537 if (index < 0)
15538 index = 0;
15539 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15540 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15541 it->it_index = index;
15542 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015543 Py_RETURN_NONE;
15544}
15545
15546PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15547
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015548static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015549 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015550 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015551 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15552 reduce_doc},
15553 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15554 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015555 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015556};
15557
15558PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015559 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15560 "str_iterator", /* tp_name */
15561 sizeof(unicodeiterobject), /* tp_basicsize */
15562 0, /* tp_itemsize */
15563 /* methods */
15564 (destructor)unicodeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020015565 0, /* tp_vectorcall_offset */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015566 0, /* tp_getattr */
15567 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020015568 0, /* tp_as_async */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015569 0, /* tp_repr */
15570 0, /* tp_as_number */
15571 0, /* tp_as_sequence */
15572 0, /* tp_as_mapping */
15573 0, /* tp_hash */
15574 0, /* tp_call */
15575 0, /* tp_str */
15576 PyObject_GenericGetAttr, /* tp_getattro */
15577 0, /* tp_setattro */
15578 0, /* tp_as_buffer */
15579 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15580 0, /* tp_doc */
15581 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15582 0, /* tp_clear */
15583 0, /* tp_richcompare */
15584 0, /* tp_weaklistoffset */
15585 PyObject_SelfIter, /* tp_iter */
15586 (iternextfunc)unicodeiter_next, /* tp_iternext */
15587 unicodeiter_methods, /* tp_methods */
15588 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015589};
15590
15591static PyObject *
15592unicode_iter(PyObject *seq)
15593{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015594 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015595
Benjamin Peterson14339b62009-01-31 16:36:08 +000015596 if (!PyUnicode_Check(seq)) {
15597 PyErr_BadInternalCall();
15598 return NULL;
15599 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015600 if (PyUnicode_READY(seq) == -1)
15601 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015602 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15603 if (it == NULL)
15604 return NULL;
15605 it->it_index = 0;
15606 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015607 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015608 _PyObject_GC_TRACK(it);
15609 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015610}
15611
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015612
15613size_t
15614Py_UNICODE_strlen(const Py_UNICODE *u)
15615{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015616 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015617}
15618
15619Py_UNICODE*
15620Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15621{
15622 Py_UNICODE *u = s1;
15623 while ((*u++ = *s2++));
15624 return s1;
15625}
15626
15627Py_UNICODE*
15628Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15629{
15630 Py_UNICODE *u = s1;
15631 while ((*u++ = *s2++))
15632 if (n-- == 0)
15633 break;
15634 return s1;
15635}
15636
15637Py_UNICODE*
15638Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15639{
15640 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015641 u1 += wcslen(u1);
15642 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015643 return s1;
15644}
15645
15646int
15647Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15648{
15649 while (*s1 && *s2 && *s1 == *s2)
15650 s1++, s2++;
15651 if (*s1 && *s2)
15652 return (*s1 < *s2) ? -1 : +1;
15653 if (*s1)
15654 return 1;
15655 if (*s2)
15656 return -1;
15657 return 0;
15658}
15659
15660int
15661Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15662{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015663 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015664 for (; n != 0; n--) {
15665 u1 = *s1;
15666 u2 = *s2;
15667 if (u1 != u2)
15668 return (u1 < u2) ? -1 : +1;
15669 if (u1 == '\0')
15670 return 0;
15671 s1++;
15672 s2++;
15673 }
15674 return 0;
15675}
15676
15677Py_UNICODE*
15678Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15679{
15680 const Py_UNICODE *p;
15681 for (p = s; *p; p++)
15682 if (*p == c)
15683 return (Py_UNICODE*)p;
15684 return NULL;
15685}
15686
15687Py_UNICODE*
15688Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15689{
15690 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015691 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015692 while (p != s) {
15693 p--;
15694 if (*p == c)
15695 return (Py_UNICODE*)p;
15696 }
15697 return NULL;
15698}
Victor Stinner331ea922010-08-10 16:37:20 +000015699
Victor Stinner71133ff2010-09-01 23:43:53 +000015700Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015701PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015702{
Victor Stinner577db2c2011-10-11 22:12:48 +020015703 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015704 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015706 if (!PyUnicode_Check(unicode)) {
15707 PyErr_BadArgument();
15708 return NULL;
15709 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015710 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015711 if (u == NULL)
15712 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015713 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015714 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015715 PyErr_NoMemory();
15716 return NULL;
15717 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015718 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015719 size *= sizeof(Py_UNICODE);
15720 copy = PyMem_Malloc(size);
15721 if (copy == NULL) {
15722 PyErr_NoMemory();
15723 return NULL;
15724 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015725 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015726 return copy;
15727}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015728
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015729
Victor Stinner709d23d2019-05-02 14:56:30 -040015730static int
15731encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015732{
Victor Stinner709d23d2019-05-02 14:56:30 -040015733 int res;
15734 res = _Py_EncodeUTF8Ex(wstr, str, NULL, NULL, 1, _Py_ERROR_STRICT);
15735 if (res == -2) {
15736 PyErr_Format(PyExc_RuntimeWarning, "cannot decode %s", name);
15737 return -1;
15738 }
15739 if (res < 0) {
15740 PyErr_NoMemory();
15741 return -1;
15742 }
15743 return 0;
15744}
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015745
Victor Stinner709d23d2019-05-02 14:56:30 -040015746
15747static int
15748config_get_codec_name(wchar_t **config_encoding)
15749{
15750 char *encoding;
15751 if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
15752 return -1;
15753 }
15754
15755 PyObject *name_obj = NULL;
15756 PyObject *codec = _PyCodec_Lookup(encoding);
15757 PyMem_RawFree(encoding);
15758
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015759 if (!codec)
15760 goto error;
15761
15762 name_obj = PyObject_GetAttrString(codec, "name");
15763 Py_CLEAR(codec);
15764 if (!name_obj) {
15765 goto error;
15766 }
15767
Victor Stinner709d23d2019-05-02 14:56:30 -040015768 wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
15769 Py_DECREF(name_obj);
15770 if (wname == NULL) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015771 goto error;
15772 }
15773
Victor Stinner709d23d2019-05-02 14:56:30 -040015774 wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
15775 if (raw_wname == NULL) {
15776 PyMem_Free(wname);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015777 PyErr_NoMemory();
Victor Stinner709d23d2019-05-02 14:56:30 -040015778 goto error;
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015779 }
Victor Stinner709d23d2019-05-02 14:56:30 -040015780
15781 PyMem_RawFree(*config_encoding);
15782 *config_encoding = raw_wname;
15783
15784 PyMem_Free(wname);
15785 return 0;
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015786
15787error:
15788 Py_XDECREF(codec);
15789 Py_XDECREF(name_obj);
Victor Stinner709d23d2019-05-02 14:56:30 -040015790 return -1;
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015791}
15792
15793
Victor Stinner331a6a52019-05-27 16:39:22 +020015794static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015795init_stdio_encoding(PyInterpreterState *interp)
15796{
Victor Stinner709d23d2019-05-02 14:56:30 -040015797 /* Update the stdio encoding to the normalized Python codec name. */
Victor Stinner331a6a52019-05-27 16:39:22 +020015798 PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -040015799 if (config_get_codec_name(&config->stdio_encoding) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015800 return _PyStatus_ERR("failed to get the Python codec name "
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015801 "of the stdio encoding");
15802 }
Victor Stinner331a6a52019-05-27 16:39:22 +020015803 return _PyStatus_OK();
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015804}
15805
15806
Victor Stinner709d23d2019-05-02 14:56:30 -040015807static int
15808init_fs_codec(PyInterpreterState *interp)
15809{
Victor Stinner331a6a52019-05-27 16:39:22 +020015810 PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -040015811
15812 _Py_error_handler error_handler;
15813 error_handler = get_error_handler_wide(config->filesystem_errors);
15814 if (error_handler == _Py_ERROR_UNKNOWN) {
15815 PyErr_SetString(PyExc_RuntimeError, "unknow filesystem error handler");
15816 return -1;
15817 }
15818
15819 char *encoding, *errors;
15820 if (encode_wstr_utf8(config->filesystem_encoding,
15821 &encoding,
15822 "filesystem_encoding") < 0) {
15823 return -1;
15824 }
15825
15826 if (encode_wstr_utf8(config->filesystem_errors,
15827 &errors,
15828 "filesystem_errors") < 0) {
15829 PyMem_RawFree(encoding);
15830 return -1;
15831 }
15832
15833 PyMem_RawFree(interp->fs_codec.encoding);
15834 interp->fs_codec.encoding = encoding;
15835 PyMem_RawFree(interp->fs_codec.errors);
15836 interp->fs_codec.errors = errors;
15837 interp->fs_codec.error_handler = error_handler;
15838
15839 /* At this point, PyUnicode_EncodeFSDefault() and
15840 PyUnicode_DecodeFSDefault() can now use the Python codec rather than
15841 the C implementation of the filesystem encoding. */
15842
15843 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
15844 global configuration variables. */
15845 if (_Py_SetFileSystemEncoding(interp->fs_codec.encoding,
15846 interp->fs_codec.errors) < 0) {
15847 PyErr_NoMemory();
15848 return -1;
15849 }
15850 return 0;
15851}
15852
15853
Victor Stinner331a6a52019-05-27 16:39:22 +020015854static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015855init_fs_encoding(PyInterpreterState *interp)
15856{
Victor Stinner709d23d2019-05-02 14:56:30 -040015857 /* Update the filesystem encoding to the normalized Python codec name.
15858 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
15859 (Python codec name). */
Victor Stinner331a6a52019-05-27 16:39:22 +020015860 PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -040015861 if (config_get_codec_name(&config->filesystem_encoding) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015862 return _PyStatus_ERR("failed to get the Python codec "
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015863 "of the filesystem encoding");
15864 }
15865
Victor Stinner709d23d2019-05-02 14:56:30 -040015866 if (init_fs_codec(interp) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015867 return _PyStatus_ERR("cannot initialize filesystem codec");
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015868 }
Victor Stinner331a6a52019-05-27 16:39:22 +020015869 return _PyStatus_OK();
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015870}
15871
15872
Victor Stinner331a6a52019-05-27 16:39:22 +020015873PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020015874_PyUnicode_InitEncodings(PyThreadState *tstate)
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015875{
Victor Stinnerb45d2592019-06-20 00:05:23 +020015876 PyInterpreterState *interp = tstate->interp;
15877
Victor Stinner331a6a52019-05-27 16:39:22 +020015878 PyStatus status = init_fs_encoding(interp);
15879 if (_PyStatus_EXCEPTION(status)) {
15880 return status;
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015881 }
15882
15883 return init_stdio_encoding(interp);
15884}
15885
15886
Victor Stinner709d23d2019-05-02 14:56:30 -040015887#ifdef MS_WINDOWS
15888int
15889_PyUnicode_EnableLegacyWindowsFSEncoding(void)
15890{
15891 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +020015892 PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -040015893
15894 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
15895 wchar_t *encoding = _PyMem_RawWcsdup(L"mbcs");
15896 wchar_t *errors = _PyMem_RawWcsdup(L"replace");
15897 if (encoding == NULL || errors == NULL) {
15898 PyMem_RawFree(encoding);
15899 PyMem_RawFree(errors);
15900 PyErr_NoMemory();
15901 return -1;
15902 }
15903
15904 PyMem_RawFree(config->filesystem_encoding);
15905 config->filesystem_encoding = encoding;
15906 PyMem_RawFree(config->filesystem_errors);
15907 config->filesystem_errors = errors;
15908
15909 return init_fs_codec(interp);
15910}
15911#endif
15912
15913
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015914void
15915_PyUnicode_Fini(void)
15916{
15917#if defined(WITH_VALGRIND) || defined(__INSURE__)
15918 /* Insure++ is a memory analysis tool that aids in discovering
15919 * memory leaks and other memory problems. On Python exit, the
15920 * interned string dictionaries are flagged as being in use at exit
15921 * (which it is). Under normal circumstances, this is fine because
15922 * the memory will be automatically reclaimed by the system. Under
15923 * memory debugging, it's a huge source of useless noise, so we
15924 * trade off slower shutdown for less distraction in the memory
15925 * reports. -baw
15926 */
15927 unicode_release_interned();
15928#endif /* __INSURE__ */
15929
15930 Py_CLEAR(unicode_empty);
15931
15932 for (Py_ssize_t i = 0; i < 256; i++) {
15933 Py_CLEAR(unicode_latin1[i]);
15934 }
15935 _PyUnicode_ClearStaticStrings();
15936 (void)PyUnicode_ClearFreeList();
Victor Stinner709d23d2019-05-02 14:56:30 -040015937
15938 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
15939 PyMem_RawFree(interp->fs_codec.encoding);
15940 interp->fs_codec.encoding = NULL;
15941 PyMem_RawFree(interp->fs_codec.errors);
15942 interp->fs_codec.errors = NULL;
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015943}
15944
15945
Georg Brandl66c221e2010-10-14 07:04:07 +000015946/* A _string module, to export formatter_parser and formatter_field_name_split
15947 to the string.Formatter class implemented in Python. */
15948
15949static PyMethodDef _string_methods[] = {
15950 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15951 METH_O, PyDoc_STR("split the argument as a field name")},
15952 {"formatter_parser", (PyCFunction) formatter_parser,
15953 METH_O, PyDoc_STR("parse the argument as a format string")},
15954 {NULL, NULL}
15955};
15956
15957static struct PyModuleDef _string_module = {
15958 PyModuleDef_HEAD_INIT,
15959 "_string",
15960 PyDoc_STR("string helper module"),
15961 0,
15962 _string_methods,
15963 NULL,
15964 NULL,
15965 NULL,
15966 NULL
15967};
15968
15969PyMODINIT_FUNC
15970PyInit__string(void)
15971{
15972 return PyModule_Create(&_string_module);
15973}
15974
15975
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015976#ifdef __cplusplus
15977}
15978#endif