blob: 1082eb4308a44e1e1cfd4dd3892c4dcf07d2568d [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 Stinnere5014be2020-04-14 17:52:15 +020043#include "pycore_abstract.h" // _PyIndex_Check()
Victor Stinner45876a92020-02-12 22:32:34 +010044#include "pycore_bytes_methods.h"
Victor Stinner9fc57a32018-11-07 00:44:03 +010045#include "pycore_fileutils.h"
Victor Stinner61691d82019-10-02 23:51:20 +020046#include "pycore_initconfig.h"
Victor Stinnere5014be2020-04-14 17:52:15 +020047#include "pycore_interp.h" // PyInterpreterState.fs_codec
Victor Stinnerbcda8f12018-11-21 22:27:47 +010048#include "pycore_object.h"
Victor Stinner61691d82019-10-02 23:51:20 +020049#include "pycore_pathconfig.h"
Victor Stinner43fc3bb2019-05-02 11:54:20 -040050#include "pycore_pylifecycle.h"
Victor Stinnere5014be2020-04-14 17:52:15 +020051#include "pycore_pystate.h" // _PyInterpreterState_GET()
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000052#include "ucnhash.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070053#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000054
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000055#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000056#include <windows.h>
57#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000058
Victor Stinnerfecc4f22019-03-19 14:20:29 +010059/* Uncomment to display statistics on interned strings at exit when
60 using Valgrind or Insecure++. */
61/* #define INTERNED_STATS 1 */
62
63
Larry Hastings61272b72014-01-07 12:41:53 -080064/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090065class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080066[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090067/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
68
69/*[python input]
70class Py_UCS4_converter(CConverter):
71 type = 'Py_UCS4'
72 converter = 'convert_uc'
73
74 def converter_init(self):
75 if self.default is not unspecified:
76 self.c_default = ascii(self.default)
77 if len(self.c_default) > 4 or self.c_default[0] != "'":
78 self.c_default = hex(ord(self.default))
79
80[python start generated code]*/
81/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080082
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000083/* --- Globals ------------------------------------------------------------
84
Serhiy Storchaka05997252013-01-26 12:14:02 +020085NOTE: In the interpreter's initialization phase, some globals are currently
86 initialized dynamically as needed. In the process Unicode objects may
87 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000088
89*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000090
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000091
92#ifdef __cplusplus
93extern "C" {
94#endif
95
Victor Stinner8faf8212011-12-08 22:14:11 +010096/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
97#define MAX_UNICODE 0x10ffff
98
Victor Stinner910337b2011-10-03 03:20:16 +020099#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200100# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +0200101#else
102# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
103#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +0200104
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200105#define _PyUnicode_UTF8(op) \
106 (((PyCompactUnicodeObject*)(op))->utf8)
107#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200108 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200109 assert(PyUnicode_IS_READY(op)), \
110 PyUnicode_IS_COMPACT_ASCII(op) ? \
111 ((char*)((PyASCIIObject*)(op) + 1)) : \
112 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200113#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200114 (((PyCompactUnicodeObject*)(op))->utf8_length)
115#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200116 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200117 assert(PyUnicode_IS_READY(op)), \
118 PyUnicode_IS_COMPACT_ASCII(op) ? \
119 ((PyASCIIObject*)(op))->length : \
120 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200121#define _PyUnicode_WSTR(op) \
122 (((PyASCIIObject*)(op))->wstr)
123#define _PyUnicode_WSTR_LENGTH(op) \
124 (((PyCompactUnicodeObject*)(op))->wstr_length)
125#define _PyUnicode_LENGTH(op) \
126 (((PyASCIIObject *)(op))->length)
127#define _PyUnicode_STATE(op) \
128 (((PyASCIIObject *)(op))->state)
129#define _PyUnicode_HASH(op) \
130 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200131#define _PyUnicode_KIND(op) \
132 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200133 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200134#define _PyUnicode_GET_LENGTH(op) \
135 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200136 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200137#define _PyUnicode_DATA_ANY(op) \
138 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200139
Victor Stinner910337b2011-10-03 03:20:16 +0200140#undef PyUnicode_READY
141#define PyUnicode_READY(op) \
142 (assert(_PyUnicode_CHECK(op)), \
143 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200144 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100145 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200146
Victor Stinnerc379ead2011-10-03 12:52:27 +0200147#define _PyUnicode_SHARE_UTF8(op) \
148 (assert(_PyUnicode_CHECK(op)), \
149 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
150 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
151#define _PyUnicode_SHARE_WSTR(op) \
152 (assert(_PyUnicode_CHECK(op)), \
153 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
154
Victor Stinner829c0ad2011-10-03 01:08:02 +0200155/* true if the Unicode object has an allocated UTF-8 memory block
156 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200157#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200158 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200159 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200160 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
161
Victor Stinner03490912011-10-03 23:45:12 +0200162/* true if the Unicode object has an allocated wstr memory block
163 (not shared with other data) */
164#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200165 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200166 (!PyUnicode_IS_READY(op) || \
167 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
168
Victor Stinner910337b2011-10-03 03:20:16 +0200169/* Generic helper macro to convert characters of different types.
170 from_type and to_type have to be valid type names, begin and end
171 are pointers to the source characters which should be of type
172 "from_type *". to is a pointer of type "to_type *" and points to the
173 buffer where the result characters are written to. */
174#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
175 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100176 to_type *_to = (to_type *)(to); \
Andy Lestere6be9b52020-02-11 20:28:35 -0600177 const from_type *_iter = (const from_type *)(begin);\
178 const from_type *_end = (const from_type *)(end);\
Antoine Pitroue459a082011-10-11 20:58:41 +0200179 Py_ssize_t n = (_end) - (_iter); \
180 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200181 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200182 while (_iter < (_unrolled_end)) { \
183 _to[0] = (to_type) _iter[0]; \
184 _to[1] = (to_type) _iter[1]; \
185 _to[2] = (to_type) _iter[2]; \
186 _to[3] = (to_type) _iter[3]; \
187 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200188 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200189 while (_iter < (_end)) \
190 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200191 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200192
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200193#ifdef MS_WINDOWS
194 /* On Windows, overallocate by 50% is the best factor */
195# define OVERALLOCATE_FACTOR 2
196#else
197 /* On Linux, overallocate by 25% is the best factor */
198# define OVERALLOCATE_FACTOR 4
199#endif
200
Victor Stinner9512ad72020-05-20 00:27:46 +0200201#define INTERNED_STRINGS
Victor Stinner607b1022020-05-05 18:50:30 +0200202
Walter Dörwald16807132007-05-25 13:52:07 +0000203/* This dictionary holds all interned unicode strings. Note that references
204 to strings in this dictionary are *not* counted in the string's ob_refcnt.
205 When the interned string reaches a refcnt of 0 the string deallocation
206 function will delete the reference from this dictionary.
207
208 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000209 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000210*/
Victor Stinner607b1022020-05-05 18:50:30 +0200211#ifdef INTERNED_STRINGS
Serhiy Storchaka05997252013-01-26 12:14:02 +0200212static PyObject *interned = NULL;
Victor Stinner607b1022020-05-05 18:50:30 +0200213#endif
Walter Dörwald16807132007-05-25 13:52:07 +0000214
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000215/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200216static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200217
Serhiy Storchaka678db842013-01-26 12:16:36 +0200218#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200219 do { \
220 if (unicode_empty != NULL) \
221 Py_INCREF(unicode_empty); \
222 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200223 unicode_empty = PyUnicode_New(0, 0); \
224 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200225 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200226 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
227 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200228 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200229 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000230
Serhiy Storchaka678db842013-01-26 12:16:36 +0200231#define _Py_RETURN_UNICODE_EMPTY() \
232 do { \
233 _Py_INCREF_UNICODE_EMPTY(); \
234 return unicode_empty; \
235 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000236
Victor Stinner59423e32018-11-26 13:40:01 +0100237static inline void
238unicode_fill(enum PyUnicode_Kind kind, void *data, Py_UCS4 value,
239 Py_ssize_t start, Py_ssize_t length)
240{
241 assert(0 <= start);
242 assert(kind != PyUnicode_WCHAR_KIND);
243 switch (kind) {
244 case PyUnicode_1BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100245 assert(value <= 0xff);
Victor Stinner59423e32018-11-26 13:40:01 +0100246 Py_UCS1 ch = (unsigned char)value;
247 Py_UCS1 *to = (Py_UCS1 *)data + start;
248 memset(to, ch, length);
249 break;
250 }
251 case PyUnicode_2BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100252 assert(value <= 0xffff);
Victor Stinner59423e32018-11-26 13:40:01 +0100253 Py_UCS2 ch = (Py_UCS2)value;
254 Py_UCS2 *to = (Py_UCS2 *)data + start;
255 const Py_UCS2 *end = to + length;
256 for (; to < end; ++to) *to = ch;
257 break;
258 }
259 case PyUnicode_4BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100260 assert(value <= MAX_UNICODE);
Victor Stinner59423e32018-11-26 13:40:01 +0100261 Py_UCS4 ch = value;
262 Py_UCS4 * to = (Py_UCS4 *)data + start;
263 const Py_UCS4 *end = to + length;
264 for (; to < end; ++to) *to = ch;
265 break;
266 }
267 default: Py_UNREACHABLE();
268 }
269}
270
271
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200272/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700273static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200274_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
Inada Naoki770847a2019-06-24 12:30:24 +0900275static inline void
276_PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer);
Victor Stinner709d23d2019-05-02 14:56:30 -0400277static PyObject *
278unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
279 const char *errors);
280static PyObject *
281unicode_decode_utf8(const char *s, Py_ssize_t size,
282 _Py_error_handler error_handler, const char *errors,
283 Py_ssize_t *consumed);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200284
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200285/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200286static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200287
Victor Stinner9512ad72020-05-20 00:27:46 +0200288#define LATIN1_SINGLETONS
Victor Stinner607b1022020-05-05 18:50:30 +0200289
290#ifdef LATIN1_SINGLETONS
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000291/* Single character Unicode strings in the Latin-1 range are being
292 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200293static PyObject *unicode_latin1[256] = {NULL};
Victor Stinner607b1022020-05-05 18:50:30 +0200294#endif
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000295
Christian Heimes190d79e2008-01-30 11:58:22 +0000296/* Fast detection of the most frequent whitespace characters */
297const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000298 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000299/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000300/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000301/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000302/* case 0x000C: * FORM FEED */
303/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000304 0, 1, 1, 1, 1, 1, 0, 0,
305 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000306/* case 0x001C: * FILE SEPARATOR */
307/* case 0x001D: * GROUP SEPARATOR */
308/* case 0x001E: * RECORD SEPARATOR */
309/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000310 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000311/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000312 1, 0, 0, 0, 0, 0, 0, 0,
313 0, 0, 0, 0, 0, 0, 0, 0,
314 0, 0, 0, 0, 0, 0, 0, 0,
315 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000316
Benjamin Peterson14339b62009-01-31 16:36:08 +0000317 0, 0, 0, 0, 0, 0, 0, 0,
318 0, 0, 0, 0, 0, 0, 0, 0,
319 0, 0, 0, 0, 0, 0, 0, 0,
320 0, 0, 0, 0, 0, 0, 0, 0,
321 0, 0, 0, 0, 0, 0, 0, 0,
322 0, 0, 0, 0, 0, 0, 0, 0,
323 0, 0, 0, 0, 0, 0, 0, 0,
324 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000325};
326
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200327/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200328static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200329static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100330static int unicode_modifiable(PyObject *unicode);
331
Victor Stinnerfe226c02011-10-03 03:52:20 +0200332
Alexander Belopolsky40018472011-02-26 01:02:56 +0000333static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100334_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200335static PyObject *
336_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
337static PyObject *
338_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
339
340static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000341unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000342 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100343 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000344 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
345
Alexander Belopolsky40018472011-02-26 01:02:56 +0000346static void
347raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300348 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100349 PyObject *unicode,
350 Py_ssize_t startpos, Py_ssize_t endpos,
351 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000352
Christian Heimes190d79e2008-01-30 11:58:22 +0000353/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200354static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000355 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000356/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000357/* 0x000B, * LINE TABULATION */
358/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000359/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000360 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000361 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000362/* 0x001C, * FILE SEPARATOR */
363/* 0x001D, * GROUP SEPARATOR */
364/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000365 0, 0, 0, 0, 1, 1, 1, 0,
366 0, 0, 0, 0, 0, 0, 0, 0,
367 0, 0, 0, 0, 0, 0, 0, 0,
368 0, 0, 0, 0, 0, 0, 0, 0,
369 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000370
Benjamin Peterson14339b62009-01-31 16:36:08 +0000371 0, 0, 0, 0, 0, 0, 0, 0,
372 0, 0, 0, 0, 0, 0, 0, 0,
373 0, 0, 0, 0, 0, 0, 0, 0,
374 0, 0, 0, 0, 0, 0, 0, 0,
375 0, 0, 0, 0, 0, 0, 0, 0,
376 0, 0, 0, 0, 0, 0, 0, 0,
377 0, 0, 0, 0, 0, 0, 0, 0,
378 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000379};
380
INADA Naoki3ae20562017-01-16 20:41:20 +0900381static int convert_uc(PyObject *obj, void *addr);
382
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300383#include "clinic/unicodeobject.c.h"
384
Victor Stinner3d4226a2018-08-29 22:21:32 +0200385_Py_error_handler
386_Py_GetErrorHandler(const char *errors)
Victor Stinner50149202015-09-22 00:26:54 +0200387{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200388 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200389 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200390 }
391 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200392 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200393 }
394 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200395 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200396 }
397 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200398 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200399 }
400 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200401 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200402 }
403 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200404 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200405 }
406 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200407 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200408 }
Victor Stinner50149202015-09-22 00:26:54 +0200409 return _Py_ERROR_OTHER;
410}
411
Victor Stinner709d23d2019-05-02 14:56:30 -0400412
413static _Py_error_handler
414get_error_handler_wide(const wchar_t *errors)
415{
416 if (errors == NULL || wcscmp(errors, L"strict") == 0) {
417 return _Py_ERROR_STRICT;
418 }
419 if (wcscmp(errors, L"surrogateescape") == 0) {
420 return _Py_ERROR_SURROGATEESCAPE;
421 }
422 if (wcscmp(errors, L"replace") == 0) {
423 return _Py_ERROR_REPLACE;
424 }
425 if (wcscmp(errors, L"ignore") == 0) {
426 return _Py_ERROR_IGNORE;
427 }
428 if (wcscmp(errors, L"backslashreplace") == 0) {
429 return _Py_ERROR_BACKSLASHREPLACE;
430 }
431 if (wcscmp(errors, L"surrogatepass") == 0) {
432 return _Py_ERROR_SURROGATEPASS;
433 }
434 if (wcscmp(errors, L"xmlcharrefreplace") == 0) {
435 return _Py_ERROR_XMLCHARREFREPLACE;
436 }
437 return _Py_ERROR_OTHER;
438}
439
440
Victor Stinner22eb6892019-06-26 00:51:05 +0200441static inline int
442unicode_check_encoding_errors(const char *encoding, const char *errors)
443{
444 if (encoding == NULL && errors == NULL) {
445 return 0;
446 }
447
Victor Stinner81a7be32020-04-14 15:14:01 +0200448 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinner22eb6892019-06-26 00:51:05 +0200449#ifndef Py_DEBUG
450 /* In release mode, only check in development mode (-X dev) */
Victor Stinnerda7933e2020-04-13 03:04:28 +0200451 if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
Victor Stinner22eb6892019-06-26 00:51:05 +0200452 return 0;
453 }
454#else
455 /* Always check in debug mode */
456#endif
457
458 /* Avoid calling _PyCodec_Lookup() and PyCodec_LookupError() before the
459 codec registry is ready: before_PyUnicode_InitEncodings() is called. */
Victor Stinner3d17c042020-05-14 01:48:38 +0200460 if (!interp->unicode.fs_codec.encoding) {
Victor Stinner22eb6892019-06-26 00:51:05 +0200461 return 0;
462 }
463
Victor Stinnerd8acf0d2020-04-07 16:07:42 +0200464 /* Disable checks during Python finalization. For example, it allows to
465 call _PyObject_Dump() during finalization for debugging purpose. */
466 if (interp->finalizing) {
467 return 0;
468 }
469
Victor Stinner22eb6892019-06-26 00:51:05 +0200470 if (encoding != NULL) {
471 PyObject *handler = _PyCodec_Lookup(encoding);
472 if (handler == NULL) {
473 return -1;
474 }
475 Py_DECREF(handler);
476 }
477
478 if (errors != NULL) {
479 PyObject *handler = PyCodec_LookupError(errors);
480 if (handler == NULL) {
481 return -1;
482 }
483 Py_DECREF(handler);
484 }
485 return 0;
486}
487
488
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300489/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
490 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000491Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000492PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000493{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000494#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000495 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000496#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000497 /* This is actually an illegal character, so it should
498 not be passed to unichr. */
499 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000500#endif
501}
502
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200503int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100504_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200505{
Victor Stinner68762572019-10-07 18:42:01 +0200506#define CHECK(expr) \
507 do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
508
Victor Stinner910337b2011-10-03 03:20:16 +0200509 PyASCIIObject *ascii;
510 unsigned int kind;
511
Victor Stinner68762572019-10-07 18:42:01 +0200512 assert(op != NULL);
513 CHECK(PyUnicode_Check(op));
Victor Stinner910337b2011-10-03 03:20:16 +0200514
515 ascii = (PyASCIIObject *)op;
516 kind = ascii->state.kind;
517
Victor Stinnera3b334d2011-10-03 13:53:37 +0200518 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner68762572019-10-07 18:42:01 +0200519 CHECK(kind == PyUnicode_1BYTE_KIND);
520 CHECK(ascii->state.ready == 1);
Victor Stinner910337b2011-10-03 03:20:16 +0200521 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200522 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200523 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200524 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200525
Victor Stinnera41463c2011-10-04 01:05:08 +0200526 if (ascii->state.compact == 1) {
527 data = compact + 1;
Victor Stinner68762572019-10-07 18:42:01 +0200528 CHECK(kind == PyUnicode_1BYTE_KIND
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200529 || kind == PyUnicode_2BYTE_KIND
530 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner68762572019-10-07 18:42:01 +0200531 CHECK(ascii->state.ascii == 0);
532 CHECK(ascii->state.ready == 1);
533 CHECK(compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100534 }
535 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200536 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
537
538 data = unicode->data.any;
539 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner68762572019-10-07 18:42:01 +0200540 CHECK(ascii->length == 0);
541 CHECK(ascii->hash == -1);
542 CHECK(ascii->state.compact == 0);
543 CHECK(ascii->state.ascii == 0);
544 CHECK(ascii->state.ready == 0);
545 CHECK(ascii->state.interned == SSTATE_NOT_INTERNED);
546 CHECK(ascii->wstr != NULL);
547 CHECK(data == NULL);
548 CHECK(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200549 }
550 else {
Victor Stinner68762572019-10-07 18:42:01 +0200551 CHECK(kind == PyUnicode_1BYTE_KIND
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200552 || kind == PyUnicode_2BYTE_KIND
553 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner68762572019-10-07 18:42:01 +0200554 CHECK(ascii->state.compact == 0);
555 CHECK(ascii->state.ready == 1);
556 CHECK(data != NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200557 if (ascii->state.ascii) {
Victor Stinner68762572019-10-07 18:42:01 +0200558 CHECK(compact->utf8 == data);
559 CHECK(compact->utf8_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200560 }
561 else
Victor Stinner68762572019-10-07 18:42:01 +0200562 CHECK(compact->utf8 != data);
Victor Stinnera41463c2011-10-04 01:05:08 +0200563 }
564 }
565 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200566 if (
567#if SIZEOF_WCHAR_T == 2
568 kind == PyUnicode_2BYTE_KIND
569#else
570 kind == PyUnicode_4BYTE_KIND
571#endif
572 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200573 {
Victor Stinner68762572019-10-07 18:42:01 +0200574 CHECK(ascii->wstr == data);
575 CHECK(compact->wstr_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200576 } else
Victor Stinner68762572019-10-07 18:42:01 +0200577 CHECK(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200578 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200579
580 if (compact->utf8 == NULL)
Victor Stinner68762572019-10-07 18:42:01 +0200581 CHECK(compact->utf8_length == 0);
Victor Stinnera41463c2011-10-04 01:05:08 +0200582 if (ascii->wstr == NULL)
Victor Stinner68762572019-10-07 18:42:01 +0200583 CHECK(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200584 }
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200585
586 /* check that the best kind is used: O(n) operation */
587 if (check_content && kind != PyUnicode_WCHAR_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200588 Py_ssize_t i;
589 Py_UCS4 maxchar = 0;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +0300590 const void *data;
Victor Stinner718fbf02012-04-26 00:39:37 +0200591 Py_UCS4 ch;
592
593 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200594 for (i=0; i < ascii->length; i++)
595 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200596 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200597 if (ch > maxchar)
598 maxchar = ch;
599 }
600 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100601 if (ascii->state.ascii == 0) {
Victor Stinner68762572019-10-07 18:42:01 +0200602 CHECK(maxchar >= 128);
603 CHECK(maxchar <= 255);
Victor Stinner77faf692011-11-20 18:56:05 +0100604 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200605 else
Victor Stinner68762572019-10-07 18:42:01 +0200606 CHECK(maxchar < 128);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200607 }
Victor Stinner77faf692011-11-20 18:56:05 +0100608 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinner68762572019-10-07 18:42:01 +0200609 CHECK(maxchar >= 0x100);
610 CHECK(maxchar <= 0xFFFF);
Victor Stinner77faf692011-11-20 18:56:05 +0100611 }
612 else {
Victor Stinner68762572019-10-07 18:42:01 +0200613 CHECK(maxchar >= 0x10000);
614 CHECK(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100615 }
Victor Stinner68762572019-10-07 18:42:01 +0200616 CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200617 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400618 return 1;
Victor Stinner68762572019-10-07 18:42:01 +0200619
620#undef CHECK
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400621}
Victor Stinner0fc91ee2019-04-12 21:51:34 +0200622
Victor Stinner910337b2011-10-03 03:20:16 +0200623
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100624static PyObject*
625unicode_result_wchar(PyObject *unicode)
626{
627#ifndef Py_DEBUG
628 Py_ssize_t len;
629
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100630 len = _PyUnicode_WSTR_LENGTH(unicode);
631 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100632 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200633 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100634 }
635
636 if (len == 1) {
637 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100638 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100639 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
640 Py_DECREF(unicode);
641 return latin1_char;
642 }
643 }
644
645 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200646 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100647 return NULL;
648 }
649#else
Victor Stinneraa771272012-10-04 02:32:58 +0200650 assert(Py_REFCNT(unicode) == 1);
651
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100652 /* don't make the result ready in debug mode to ensure that the caller
653 makes the string ready before using it */
654 assert(_PyUnicode_CheckConsistency(unicode, 1));
655#endif
656 return unicode;
657}
658
659static PyObject*
660unicode_result_ready(PyObject *unicode)
661{
662 Py_ssize_t length;
663
664 length = PyUnicode_GET_LENGTH(unicode);
665 if (length == 0) {
666 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100667 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200668 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100669 }
670 return unicode_empty;
671 }
672
Victor Stinner607b1022020-05-05 18:50:30 +0200673#ifdef LATIN1_SINGLETONS
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100674 if (length == 1) {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +0300675 const void *data = PyUnicode_DATA(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +0200676 int kind = PyUnicode_KIND(unicode);
677 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100678 if (ch < 256) {
679 PyObject *latin1_char = unicode_latin1[ch];
680 if (latin1_char != NULL) {
681 if (unicode != latin1_char) {
682 Py_INCREF(latin1_char);
683 Py_DECREF(unicode);
684 }
685 return latin1_char;
686 }
687 else {
688 assert(_PyUnicode_CheckConsistency(unicode, 1));
689 Py_INCREF(unicode);
690 unicode_latin1[ch] = unicode;
691 return unicode;
692 }
693 }
694 }
Victor Stinner607b1022020-05-05 18:50:30 +0200695#endif
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100696
697 assert(_PyUnicode_CheckConsistency(unicode, 1));
698 return unicode;
699}
700
701static PyObject*
702unicode_result(PyObject *unicode)
703{
704 assert(_PyUnicode_CHECK(unicode));
705 if (PyUnicode_IS_READY(unicode))
706 return unicode_result_ready(unicode);
707 else
708 return unicode_result_wchar(unicode);
709}
710
Victor Stinnerc4b49542011-12-11 22:44:26 +0100711static PyObject*
712unicode_result_unchanged(PyObject *unicode)
713{
714 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500715 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100716 return NULL;
717 Py_INCREF(unicode);
718 return unicode;
719 }
720 else
721 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100722 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100723}
724
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200725/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
726 ASCII, Latin1, UTF-8, etc. */
727static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200728backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200729 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
730{
Victor Stinnerad771582015-10-09 12:38:53 +0200731 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200732 Py_UCS4 ch;
733 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +0300734 const void *data;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200735
736 assert(PyUnicode_IS_READY(unicode));
737 kind = PyUnicode_KIND(unicode);
738 data = PyUnicode_DATA(unicode);
739
740 size = 0;
741 /* determine replacement size */
742 for (i = collstart; i < collend; ++i) {
743 Py_ssize_t incr;
744
745 ch = PyUnicode_READ(kind, data, i);
746 if (ch < 0x100)
747 incr = 2+2;
748 else if (ch < 0x10000)
749 incr = 2+4;
750 else {
751 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200752 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200753 }
754 if (size > PY_SSIZE_T_MAX - incr) {
755 PyErr_SetString(PyExc_OverflowError,
756 "encoded result is too long for a Python string");
757 return NULL;
758 }
759 size += incr;
760 }
761
Victor Stinnerad771582015-10-09 12:38:53 +0200762 str = _PyBytesWriter_Prepare(writer, str, size);
763 if (str == NULL)
764 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200765
766 /* generate replacement */
767 for (i = collstart; i < collend; ++i) {
768 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200769 *str++ = '\\';
770 if (ch >= 0x00010000) {
771 *str++ = 'U';
772 *str++ = Py_hexdigits[(ch>>28)&0xf];
773 *str++ = Py_hexdigits[(ch>>24)&0xf];
774 *str++ = Py_hexdigits[(ch>>20)&0xf];
775 *str++ = Py_hexdigits[(ch>>16)&0xf];
776 *str++ = Py_hexdigits[(ch>>12)&0xf];
777 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200778 }
Victor Stinner797485e2015-10-09 03:17:30 +0200779 else if (ch >= 0x100) {
780 *str++ = 'u';
781 *str++ = Py_hexdigits[(ch>>12)&0xf];
782 *str++ = Py_hexdigits[(ch>>8)&0xf];
783 }
784 else
785 *str++ = 'x';
786 *str++ = Py_hexdigits[(ch>>4)&0xf];
787 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200788 }
789 return str;
790}
791
792/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
793 ASCII, Latin1, UTF-8, etc. */
794static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200795xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200796 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
797{
Victor Stinnerad771582015-10-09 12:38:53 +0200798 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200799 Py_UCS4 ch;
800 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +0300801 const void *data;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200802
803 assert(PyUnicode_IS_READY(unicode));
804 kind = PyUnicode_KIND(unicode);
805 data = PyUnicode_DATA(unicode);
806
807 size = 0;
808 /* determine replacement size */
809 for (i = collstart; i < collend; ++i) {
810 Py_ssize_t incr;
811
812 ch = PyUnicode_READ(kind, data, i);
813 if (ch < 10)
814 incr = 2+1+1;
815 else if (ch < 100)
816 incr = 2+2+1;
817 else if (ch < 1000)
818 incr = 2+3+1;
819 else if (ch < 10000)
820 incr = 2+4+1;
821 else if (ch < 100000)
822 incr = 2+5+1;
823 else if (ch < 1000000)
824 incr = 2+6+1;
825 else {
826 assert(ch <= MAX_UNICODE);
827 incr = 2+7+1;
828 }
829 if (size > PY_SSIZE_T_MAX - incr) {
830 PyErr_SetString(PyExc_OverflowError,
831 "encoded result is too long for a Python string");
832 return NULL;
833 }
834 size += incr;
835 }
836
Victor Stinnerad771582015-10-09 12:38:53 +0200837 str = _PyBytesWriter_Prepare(writer, str, size);
838 if (str == NULL)
839 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200840
841 /* generate replacement */
842 for (i = collstart; i < collend; ++i) {
843 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
844 }
845 return str;
846}
847
Thomas Wouters477c8d52006-05-27 19:21:47 +0000848/* --- Bloom Filters ----------------------------------------------------- */
849
850/* stuff to implement simple "bloom filters" for Unicode characters.
851 to keep things simple, we use a single bitmask, using the least 5
852 bits from each unicode characters as the bit index. */
853
854/* the linebreak mask is set up by Unicode_Init below */
855
Antoine Pitrouf068f942010-01-13 14:19:12 +0000856#if LONG_BIT >= 128
857#define BLOOM_WIDTH 128
858#elif LONG_BIT >= 64
859#define BLOOM_WIDTH 64
860#elif LONG_BIT >= 32
861#define BLOOM_WIDTH 32
862#else
863#error "LONG_BIT is smaller than 32"
864#endif
865
Thomas Wouters477c8d52006-05-27 19:21:47 +0000866#define BLOOM_MASK unsigned long
867
Serhiy Storchaka05997252013-01-26 12:14:02 +0200868static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000869
Antoine Pitrouf068f942010-01-13 14:19:12 +0000870#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000871
Benjamin Peterson29060642009-01-31 22:14:21 +0000872#define BLOOM_LINEBREAK(ch) \
873 ((ch) < 128U ? ascii_linebreak[(ch)] : \
874 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000875
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700876static inline BLOOM_MASK
Serhiy Storchakacd8295f2020-04-11 10:48:40 +0300877make_bloom_mask(int kind, const void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000878{
Victor Stinnera85af502013-04-09 21:53:54 +0200879#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
880 do { \
881 TYPE *data = (TYPE *)PTR; \
882 TYPE *end = data + LEN; \
883 Py_UCS4 ch; \
884 for (; data != end; data++) { \
885 ch = *data; \
886 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
887 } \
888 break; \
889 } while (0)
890
Thomas Wouters477c8d52006-05-27 19:21:47 +0000891 /* calculate simple bloom-style bitmask for a given unicode string */
892
Antoine Pitrouf068f942010-01-13 14:19:12 +0000893 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000894
895 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200896 switch (kind) {
897 case PyUnicode_1BYTE_KIND:
898 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
899 break;
900 case PyUnicode_2BYTE_KIND:
901 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
902 break;
903 case PyUnicode_4BYTE_KIND:
904 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
905 break;
906 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700907 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200908 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000909 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200910
911#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000912}
913
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300914static int
915ensure_unicode(PyObject *obj)
916{
917 if (!PyUnicode_Check(obj)) {
918 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +0200919 "must be str, not %.100s",
920 Py_TYPE(obj)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300921 return -1;
922 }
923 return PyUnicode_READY(obj);
924}
925
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200926/* Compilation of templated routines */
927
928#include "stringlib/asciilib.h"
929#include "stringlib/fastsearch.h"
930#include "stringlib/partition.h"
931#include "stringlib/split.h"
932#include "stringlib/count.h"
933#include "stringlib/find.h"
934#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200935#include "stringlib/undef.h"
936
937#include "stringlib/ucs1lib.h"
938#include "stringlib/fastsearch.h"
939#include "stringlib/partition.h"
940#include "stringlib/split.h"
941#include "stringlib/count.h"
942#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300943#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200944#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200945#include "stringlib/undef.h"
946
947#include "stringlib/ucs2lib.h"
948#include "stringlib/fastsearch.h"
949#include "stringlib/partition.h"
950#include "stringlib/split.h"
951#include "stringlib/count.h"
952#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300953#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200954#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200955#include "stringlib/undef.h"
956
957#include "stringlib/ucs4lib.h"
958#include "stringlib/fastsearch.h"
959#include "stringlib/partition.h"
960#include "stringlib/split.h"
961#include "stringlib/count.h"
962#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300963#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200964#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200965#include "stringlib/undef.h"
966
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200967#include "stringlib/unicodedefs.h"
968#include "stringlib/fastsearch.h"
969#include "stringlib/count.h"
970#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100971#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200972
Guido van Rossumd57fd912000-03-10 22:53:23 +0000973/* --- Unicode Object ----------------------------------------------------- */
974
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700975static inline Py_ssize_t
976findchar(const void *s, int kind,
977 Py_ssize_t size, Py_UCS4 ch,
978 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200980 switch (kind) {
981 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200982 if ((Py_UCS1) ch != ch)
983 return -1;
984 if (direction > 0)
Andy Lestere6be9b52020-02-11 20:28:35 -0600985 return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200986 else
Andy Lestere6be9b52020-02-11 20:28:35 -0600987 return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200988 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200989 if ((Py_UCS2) ch != ch)
990 return -1;
991 if (direction > 0)
Andy Lestere6be9b52020-02-11 20:28:35 -0600992 return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200993 else
Andy Lestere6be9b52020-02-11 20:28:35 -0600994 return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200995 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200996 if (direction > 0)
Andy Lestere6be9b52020-02-11 20:28:35 -0600997 return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200998 else
Andy Lestere6be9b52020-02-11 20:28:35 -0600999 return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02001000 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07001001 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +02001002 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001003}
1004
Victor Stinnerafffce42012-10-03 23:03:17 +02001005#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +00001006/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +02001007 earlier.
1008
1009 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
1010 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
1011 invalid character in Unicode 6.0. */
1012static void
1013unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
1014{
1015 int kind = PyUnicode_KIND(unicode);
1016 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
1017 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
1018 if (length <= old_length)
1019 return;
1020 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
1021}
1022#endif
1023
Victor Stinnerfe226c02011-10-03 03:52:20 +02001024static PyObject*
1025resize_compact(PyObject *unicode, Py_ssize_t length)
1026{
1027 Py_ssize_t char_size;
1028 Py_ssize_t struct_size;
1029 Py_ssize_t new_size;
1030 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +01001031 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +02001032#ifdef Py_DEBUG
1033 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1034#endif
1035
Victor Stinner79891572012-05-03 13:43:07 +02001036 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001037 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +01001038 assert(PyUnicode_IS_COMPACT(unicode));
1039
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001040 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +01001041 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +02001042 struct_size = sizeof(PyASCIIObject);
1043 else
1044 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +02001045 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046
Victor Stinnerfe226c02011-10-03 03:52:20 +02001047 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
1048 PyErr_NoMemory();
1049 return NULL;
1050 }
1051 new_size = (struct_size + (length + 1) * char_size);
1052
Serhiy Storchaka7aa69082015-12-03 01:02:03 +02001053 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
1054 PyObject_DEL(_PyUnicode_UTF8(unicode));
1055 _PyUnicode_UTF8(unicode) = NULL;
1056 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1057 }
Victor Stinner49932fe2020-02-03 17:55:05 +01001058#ifdef Py_REF_DEBUG
1059 _Py_RefTotal--;
1060#endif
1061#ifdef Py_TRACE_REFS
Victor Stinner84def372011-12-11 20:04:56 +01001062 _Py_ForgetReference(unicode);
Victor Stinner49932fe2020-02-03 17:55:05 +01001063#endif
Victor Stinner84def372011-12-11 20:04:56 +01001064
Serhiy Storchaka20b39b22014-09-28 11:27:24 +03001065 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +01001066 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001067 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001068 PyErr_NoMemory();
1069 return NULL;
1070 }
Victor Stinner84def372011-12-11 20:04:56 +01001071 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001072 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +01001073
Victor Stinnerfe226c02011-10-03 03:52:20 +02001074 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001075 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001076 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +01001077 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +02001078 _PyUnicode_WSTR_LENGTH(unicode) = length;
1079 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01001080 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
1081 PyObject_DEL(_PyUnicode_WSTR(unicode));
1082 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +01001083 if (!PyUnicode_IS_ASCII(unicode))
1084 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01001085 }
Victor Stinnerafffce42012-10-03 23:03:17 +02001086#ifdef Py_DEBUG
1087 unicode_fill_invalid(unicode, old_length);
1088#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001089 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
1090 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +02001091 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001092 return unicode;
1093}
1094
Alexander Belopolsky40018472011-02-26 01:02:56 +00001095static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001096resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001097{
Victor Stinner95663112011-10-04 01:03:50 +02001098 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001099 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001100 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001101 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +00001102
Victor Stinnerfe226c02011-10-03 03:52:20 +02001103 if (PyUnicode_IS_READY(unicode)) {
1104 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001105 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001106 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +02001107#ifdef Py_DEBUG
1108 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1109#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001110
1111 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001112 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +02001113 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
1114 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001115
1116 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1117 PyErr_NoMemory();
1118 return -1;
1119 }
1120 new_size = (length + 1) * char_size;
1121
Victor Stinner7a9105a2011-12-12 00:13:42 +01001122 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1123 {
1124 PyObject_DEL(_PyUnicode_UTF8(unicode));
1125 _PyUnicode_UTF8(unicode) = NULL;
1126 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1127 }
1128
Victor Stinnerfe226c02011-10-03 03:52:20 +02001129 data = (PyObject *)PyObject_REALLOC(data, new_size);
1130 if (data == NULL) {
1131 PyErr_NoMemory();
1132 return -1;
1133 }
1134 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001135 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001136 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001137 _PyUnicode_WSTR_LENGTH(unicode) = length;
1138 }
1139 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001140 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001141 _PyUnicode_UTF8_LENGTH(unicode) = length;
1142 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001143 _PyUnicode_LENGTH(unicode) = length;
1144 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001145#ifdef Py_DEBUG
1146 unicode_fill_invalid(unicode, old_length);
1147#endif
Victor Stinner95663112011-10-04 01:03:50 +02001148 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001149 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001150 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001151 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001152 }
Victor Stinner95663112011-10-04 01:03:50 +02001153 assert(_PyUnicode_WSTR(unicode) != NULL);
1154
1155 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001156 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001157 PyErr_NoMemory();
1158 return -1;
1159 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001160 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001161 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001162 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001163 if (!wstr) {
1164 PyErr_NoMemory();
1165 return -1;
1166 }
1167 _PyUnicode_WSTR(unicode) = wstr;
1168 _PyUnicode_WSTR(unicode)[length] = 0;
1169 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001170 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001171 return 0;
1172}
1173
Victor Stinnerfe226c02011-10-03 03:52:20 +02001174static PyObject*
1175resize_copy(PyObject *unicode, Py_ssize_t length)
1176{
1177 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001178 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001179 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001180
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001181 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001182
1183 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1184 if (copy == NULL)
1185 return NULL;
1186
1187 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001188 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001189 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001190 }
1191 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001192 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001193
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001194 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001195 if (w == NULL)
1196 return NULL;
1197 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1198 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001199 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001200 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001201 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001202 }
1203}
1204
Guido van Rossumd57fd912000-03-10 22:53:23 +00001205/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001206 Ux0000 terminated; some code (e.g. new_identifier)
1207 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001208
1209 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001210 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001211
1212*/
1213
Alexander Belopolsky40018472011-02-26 01:02:56 +00001214static PyUnicodeObject *
1215_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001216{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001217 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001219
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001221 if (length == 0 && unicode_empty != NULL) {
1222 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001223 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001224 }
1225
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001226 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001227 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001228 return (PyUnicodeObject *)PyErr_NoMemory();
1229 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001230 if (length < 0) {
1231 PyErr_SetString(PyExc_SystemError,
1232 "Negative size passed to _PyUnicode_New");
1233 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001234 }
1235
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001236 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1237 if (unicode == NULL)
1238 return NULL;
1239 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001240
1241 _PyUnicode_WSTR_LENGTH(unicode) = length;
1242 _PyUnicode_HASH(unicode) = -1;
1243 _PyUnicode_STATE(unicode).interned = 0;
1244 _PyUnicode_STATE(unicode).kind = 0;
1245 _PyUnicode_STATE(unicode).compact = 0;
1246 _PyUnicode_STATE(unicode).ready = 0;
1247 _PyUnicode_STATE(unicode).ascii = 0;
1248 _PyUnicode_DATA_ANY(unicode) = NULL;
1249 _PyUnicode_LENGTH(unicode) = 0;
1250 _PyUnicode_UTF8(unicode) = NULL;
1251 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001253 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1254 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001255 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001256 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001257 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001258 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001259
Jeremy Hyltond8082792003-09-16 19:41:39 +00001260 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001261 * the caller fails before initializing str -- unicode_resize()
1262 * reads str[0], and the Keep-Alive optimization can keep memory
1263 * allocated for str alive across a call to unicode_dealloc(unicode).
1264 * We don't want unicode_resize to read uninitialized memory in
1265 * that case.
1266 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001267 _PyUnicode_WSTR(unicode)[0] = 0;
1268 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001269
Victor Stinner7931d9a2011-11-04 00:22:48 +01001270 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001271 return unicode;
1272}
1273
Victor Stinnerf42dc442011-10-02 23:33:16 +02001274static const char*
1275unicode_kind_name(PyObject *unicode)
1276{
Victor Stinner42dfd712011-10-03 14:41:45 +02001277 /* don't check consistency: unicode_kind_name() is called from
1278 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001279 if (!PyUnicode_IS_COMPACT(unicode))
1280 {
1281 if (!PyUnicode_IS_READY(unicode))
1282 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001283 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001284 {
1285 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001286 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001287 return "legacy ascii";
1288 else
1289 return "legacy latin1";
1290 case PyUnicode_2BYTE_KIND:
1291 return "legacy UCS2";
1292 case PyUnicode_4BYTE_KIND:
1293 return "legacy UCS4";
1294 default:
1295 return "<legacy invalid kind>";
1296 }
1297 }
1298 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001299 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001300 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001301 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001302 return "ascii";
1303 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001304 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001305 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001306 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001307 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001308 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001309 default:
1310 return "<invalid compact kind>";
1311 }
1312}
1313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315/* Functions wrapping macros for use in debugger */
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001316const char *_PyUnicode_utf8(void *unicode_raw){
Victor Stinnera42de742018-11-22 10:25:22 +01001317 PyObject *unicode = _PyObject_CAST(unicode_raw);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001318 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319}
1320
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001321const void *_PyUnicode_compact_data(void *unicode_raw) {
Victor Stinnera42de742018-11-22 10:25:22 +01001322 PyObject *unicode = _PyObject_CAST(unicode_raw);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 return _PyUnicode_COMPACT_DATA(unicode);
1324}
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001325const void *_PyUnicode_data(void *unicode_raw) {
Victor Stinnera42de742018-11-22 10:25:22 +01001326 PyObject *unicode = _PyObject_CAST(unicode_raw);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001327 printf("obj %p\n", (void*)unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001328 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1329 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1330 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1331 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1332 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1333 return PyUnicode_DATA(unicode);
1334}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001335
1336void
1337_PyUnicode_Dump(PyObject *op)
1338{
1339 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001340 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1341 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001342 const void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001343
Victor Stinnera849a4b2011-10-03 12:12:11 +02001344 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001345 {
1346 if (ascii->state.ascii)
1347 data = (ascii + 1);
1348 else
1349 data = (compact + 1);
1350 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001351 else
1352 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001353 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1354 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001355
Victor Stinnera849a4b2011-10-03 12:12:11 +02001356 if (ascii->wstr == data)
1357 printf("shared ");
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001358 printf("wstr=%p", (void *)ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001359
Victor Stinnera3b334d2011-10-03 13:53:37 +02001360 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001361 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001362 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1363 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001364 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001365 (void *)compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001366 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001367 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001368}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001369#endif
1370
1371PyObject *
1372PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1373{
1374 PyObject *obj;
1375 PyCompactUnicodeObject *unicode;
1376 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001377 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001378 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001379 Py_ssize_t char_size;
1380 Py_ssize_t struct_size;
1381
1382 /* Optimization for empty strings */
1383 if (size == 0 && unicode_empty != NULL) {
1384 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001385 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 }
1387
Victor Stinner9e9d6892011-10-04 01:02:02 +02001388 is_ascii = 0;
1389 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 struct_size = sizeof(PyCompactUnicodeObject);
1391 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001392 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393 char_size = 1;
1394 is_ascii = 1;
1395 struct_size = sizeof(PyASCIIObject);
1396 }
1397 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001398 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 char_size = 1;
1400 }
1401 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001402 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 char_size = 2;
1404 if (sizeof(wchar_t) == 2)
1405 is_sharing = 1;
1406 }
1407 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001408 if (maxchar > MAX_UNICODE) {
1409 PyErr_SetString(PyExc_SystemError,
1410 "invalid maximum character passed to PyUnicode_New");
1411 return NULL;
1412 }
Victor Stinner8f825062012-04-27 13:55:39 +02001413 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001414 char_size = 4;
1415 if (sizeof(wchar_t) == 4)
1416 is_sharing = 1;
1417 }
1418
1419 /* Ensure we won't overflow the size. */
1420 if (size < 0) {
1421 PyErr_SetString(PyExc_SystemError,
1422 "Negative size passed to PyUnicode_New");
1423 return NULL;
1424 }
1425 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1426 return PyErr_NoMemory();
1427
1428 /* Duplicated allocation code from _PyObject_New() instead of a call to
1429 * PyObject_New() so we are able to allocate space for the object and
1430 * it's data buffer.
1431 */
1432 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1433 if (obj == NULL)
1434 return PyErr_NoMemory();
1435 obj = PyObject_INIT(obj, &PyUnicode_Type);
1436 if (obj == NULL)
1437 return NULL;
1438
1439 unicode = (PyCompactUnicodeObject *)obj;
1440 if (is_ascii)
1441 data = ((PyASCIIObject*)obj) + 1;
1442 else
1443 data = unicode + 1;
1444 _PyUnicode_LENGTH(unicode) = size;
1445 _PyUnicode_HASH(unicode) = -1;
1446 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001447 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001448 _PyUnicode_STATE(unicode).compact = 1;
1449 _PyUnicode_STATE(unicode).ready = 1;
1450 _PyUnicode_STATE(unicode).ascii = is_ascii;
1451 if (is_ascii) {
1452 ((char*)data)[size] = 0;
1453 _PyUnicode_WSTR(unicode) = NULL;
1454 }
Victor Stinner8f825062012-04-27 13:55:39 +02001455 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456 ((char*)data)[size] = 0;
1457 _PyUnicode_WSTR(unicode) = NULL;
1458 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001459 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001460 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001462 else {
1463 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001464 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001465 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001466 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001467 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001468 ((Py_UCS4*)data)[size] = 0;
1469 if (is_sharing) {
1470 _PyUnicode_WSTR_LENGTH(unicode) = size;
1471 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1472 }
1473 else {
1474 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1475 _PyUnicode_WSTR(unicode) = NULL;
1476 }
1477 }
Victor Stinner8f825062012-04-27 13:55:39 +02001478#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001479 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001480#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001481 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001482 return obj;
1483}
1484
1485#if SIZEOF_WCHAR_T == 2
1486/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1487 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001488 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001489
1490 This function assumes that unicode can hold one more code point than wstr
1491 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001492static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001493unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001494 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001495{
1496 const wchar_t *iter;
1497 Py_UCS4 *ucs4_out;
1498
Victor Stinner910337b2011-10-03 03:20:16 +02001499 assert(unicode != NULL);
1500 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001501 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1502 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1503
1504 for (iter = begin; iter < end; ) {
1505 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1506 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001507 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1508 && (iter+1) < end
1509 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001510 {
Victor Stinner551ac952011-11-29 22:58:13 +01001511 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001512 iter += 2;
1513 }
1514 else {
1515 *ucs4_out++ = *iter;
1516 iter++;
1517 }
1518 }
1519 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1520 _PyUnicode_GET_LENGTH(unicode)));
1521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001522}
1523#endif
1524
Victor Stinnercd9950f2011-10-02 00:34:53 +02001525static int
Victor Stinner488fa492011-12-12 00:01:39 +01001526unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001527{
Victor Stinner488fa492011-12-12 00:01:39 +01001528 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001529 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001530 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001531 return -1;
1532 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001533 return 0;
1534}
1535
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001536static int
1537_copy_characters(PyObject *to, Py_ssize_t to_start,
1538 PyObject *from, Py_ssize_t from_start,
1539 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001540{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001541 unsigned int from_kind, to_kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001542 const void *from_data;
1543 void *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001544
Victor Stinneree4544c2012-05-09 22:24:08 +02001545 assert(0 <= how_many);
1546 assert(0 <= from_start);
1547 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001548 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001549 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001550 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001551
Victor Stinnerd3f08822012-05-29 12:57:52 +02001552 assert(PyUnicode_Check(to));
1553 assert(PyUnicode_IS_READY(to));
1554 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1555
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001556 if (how_many == 0)
1557 return 0;
1558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001559 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001560 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001561 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001562 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001563
Victor Stinnerf1852262012-06-16 16:38:26 +02001564#ifdef Py_DEBUG
1565 if (!check_maxchar
1566 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1567 {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001568 Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerf1852262012-06-16 16:38:26 +02001569 Py_UCS4 ch;
1570 Py_ssize_t i;
1571 for (i=0; i < how_many; i++) {
1572 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1573 assert(ch <= to_maxchar);
1574 }
1575 }
1576#endif
1577
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001578 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001579 if (check_maxchar
1580 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1581 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001582 /* Writing Latin-1 characters into an ASCII string requires to
1583 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001584 Py_UCS4 max_char;
1585 max_char = ucs1lib_find_max_char(from_data,
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001586 (const Py_UCS1*)from_data + how_many);
Victor Stinnerf1852262012-06-16 16:38:26 +02001587 if (max_char >= 128)
1588 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001589 }
Christian Heimesf051e432016-09-13 20:22:02 +02001590 memcpy((char*)to_data + to_kind * to_start,
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03001591 (const char*)from_data + from_kind * from_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001592 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001593 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001594 else if (from_kind == PyUnicode_1BYTE_KIND
1595 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001596 {
1597 _PyUnicode_CONVERT_BYTES(
1598 Py_UCS1, Py_UCS2,
1599 PyUnicode_1BYTE_DATA(from) + from_start,
1600 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1601 PyUnicode_2BYTE_DATA(to) + to_start
1602 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001603 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001604 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001605 && to_kind == PyUnicode_4BYTE_KIND)
1606 {
1607 _PyUnicode_CONVERT_BYTES(
1608 Py_UCS1, Py_UCS4,
1609 PyUnicode_1BYTE_DATA(from) + from_start,
1610 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1611 PyUnicode_4BYTE_DATA(to) + to_start
1612 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001613 }
1614 else if (from_kind == PyUnicode_2BYTE_KIND
1615 && to_kind == PyUnicode_4BYTE_KIND)
1616 {
1617 _PyUnicode_CONVERT_BYTES(
1618 Py_UCS2, Py_UCS4,
1619 PyUnicode_2BYTE_DATA(from) + from_start,
1620 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1621 PyUnicode_4BYTE_DATA(to) + to_start
1622 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001623 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001624 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001625 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1626
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001627 if (!check_maxchar) {
1628 if (from_kind == PyUnicode_2BYTE_KIND
1629 && to_kind == PyUnicode_1BYTE_KIND)
1630 {
1631 _PyUnicode_CONVERT_BYTES(
1632 Py_UCS2, Py_UCS1,
1633 PyUnicode_2BYTE_DATA(from) + from_start,
1634 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1635 PyUnicode_1BYTE_DATA(to) + to_start
1636 );
1637 }
1638 else if (from_kind == PyUnicode_4BYTE_KIND
1639 && to_kind == PyUnicode_1BYTE_KIND)
1640 {
1641 _PyUnicode_CONVERT_BYTES(
1642 Py_UCS4, Py_UCS1,
1643 PyUnicode_4BYTE_DATA(from) + from_start,
1644 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1645 PyUnicode_1BYTE_DATA(to) + to_start
1646 );
1647 }
1648 else if (from_kind == PyUnicode_4BYTE_KIND
1649 && to_kind == PyUnicode_2BYTE_KIND)
1650 {
1651 _PyUnicode_CONVERT_BYTES(
1652 Py_UCS4, Py_UCS2,
1653 PyUnicode_4BYTE_DATA(from) + from_start,
1654 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1655 PyUnicode_2BYTE_DATA(to) + to_start
1656 );
1657 }
1658 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001659 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001660 }
1661 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001662 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001663 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001664 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001665 Py_ssize_t i;
1666
Victor Stinnera0702ab2011-09-29 14:14:38 +02001667 for (i=0; i < how_many; i++) {
1668 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001669 if (ch > to_maxchar)
1670 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001671 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1672 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001673 }
1674 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001675 return 0;
1676}
1677
Victor Stinnerd3f08822012-05-29 12:57:52 +02001678void
1679_PyUnicode_FastCopyCharacters(
1680 PyObject *to, Py_ssize_t to_start,
1681 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001682{
1683 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1684}
1685
1686Py_ssize_t
1687PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1688 PyObject *from, Py_ssize_t from_start,
1689 Py_ssize_t how_many)
1690{
1691 int err;
1692
1693 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1694 PyErr_BadInternalCall();
1695 return -1;
1696 }
1697
Benjamin Petersonbac79492012-01-14 13:34:47 -05001698 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001699 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001700 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001701 return -1;
1702
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001703 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001704 PyErr_SetString(PyExc_IndexError, "string index out of range");
1705 return -1;
1706 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001707 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001708 PyErr_SetString(PyExc_IndexError, "string index out of range");
1709 return -1;
1710 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001711 if (how_many < 0) {
1712 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1713 return -1;
1714 }
1715 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001716 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1717 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001718 "Cannot write %zi characters at %zi "
1719 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001720 how_many, to_start, PyUnicode_GET_LENGTH(to));
1721 return -1;
1722 }
1723
1724 if (how_many == 0)
1725 return 0;
1726
Victor Stinner488fa492011-12-12 00:01:39 +01001727 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001728 return -1;
1729
1730 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1731 if (err) {
1732 PyErr_Format(PyExc_SystemError,
1733 "Cannot copy %s characters "
1734 "into a string of %s characters",
1735 unicode_kind_name(from),
1736 unicode_kind_name(to));
1737 return -1;
1738 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001739 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001740}
1741
Victor Stinner17222162011-09-28 22:15:37 +02001742/* Find the maximum code point and count the number of surrogate pairs so a
1743 correct string length can be computed before converting a string to UCS4.
1744 This function counts single surrogates as a character and not as a pair.
1745
1746 Return 0 on success, or -1 on error. */
1747static int
1748find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1749 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750{
1751 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001752 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001753
Victor Stinnerc53be962011-10-02 21:33:54 +02001754 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 *num_surrogates = 0;
1756 *maxchar = 0;
1757
1758 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001760 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1761 && (iter+1) < end
1762 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1763 {
1764 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1765 ++(*num_surrogates);
1766 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 }
1768 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001770 {
1771 ch = *iter;
1772 iter++;
1773 }
1774 if (ch > *maxchar) {
1775 *maxchar = ch;
1776 if (*maxchar > MAX_UNICODE) {
1777 PyErr_Format(PyExc_ValueError,
1778 "character U+%x is not in range [U+0000; U+10ffff]",
1779 ch);
1780 return -1;
1781 }
1782 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783 }
1784 return 0;
1785}
1786
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001787int
1788_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001789{
1790 wchar_t *end;
1791 Py_UCS4 maxchar = 0;
1792 Py_ssize_t num_surrogates;
1793#if SIZEOF_WCHAR_T == 2
1794 Py_ssize_t length_wo_surrogates;
1795#endif
1796
Georg Brandl7597add2011-10-05 16:36:47 +02001797 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001798 strings were created using _PyObject_New() and where no canonical
1799 representation (the str field) has been set yet aka strings
1800 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001801 assert(_PyUnicode_CHECK(unicode));
1802 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001803 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001804 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001805 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001806 /* Actually, it should neither be interned nor be anything else: */
1807 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001810 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001811 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001812 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001813
1814 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001815 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1816 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001817 PyErr_NoMemory();
1818 return -1;
1819 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001820 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001821 _PyUnicode_WSTR(unicode), end,
1822 PyUnicode_1BYTE_DATA(unicode));
1823 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1824 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1825 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1826 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001827 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001828 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001829 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830 }
1831 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001832 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001833 _PyUnicode_UTF8(unicode) = NULL;
1834 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001835 }
1836 PyObject_FREE(_PyUnicode_WSTR(unicode));
1837 _PyUnicode_WSTR(unicode) = NULL;
1838 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1839 }
1840 /* In this case we might have to convert down from 4-byte native
1841 wchar_t to 2-byte unicode. */
1842 else if (maxchar < 65536) {
1843 assert(num_surrogates == 0 &&
1844 "FindMaxCharAndNumSurrogatePairs() messed up");
1845
Victor Stinner506f5922011-09-28 22:34:18 +02001846#if SIZEOF_WCHAR_T == 2
1847 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001848 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001849 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1850 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1851 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001852 _PyUnicode_UTF8(unicode) = NULL;
1853 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001854#else
1855 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001856 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001857 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001858 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001859 PyErr_NoMemory();
1860 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001861 }
Victor Stinner506f5922011-09-28 22:34:18 +02001862 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1863 _PyUnicode_WSTR(unicode), end,
1864 PyUnicode_2BYTE_DATA(unicode));
1865 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1866 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1867 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001868 _PyUnicode_UTF8(unicode) = NULL;
1869 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001870 PyObject_FREE(_PyUnicode_WSTR(unicode));
1871 _PyUnicode_WSTR(unicode) = NULL;
1872 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1873#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001874 }
1875 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1876 else {
1877#if SIZEOF_WCHAR_T == 2
1878 /* in case the native representation is 2-bytes, we need to allocate a
1879 new normalized 4-byte version. */
1880 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001881 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1882 PyErr_NoMemory();
1883 return -1;
1884 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001885 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1886 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001887 PyErr_NoMemory();
1888 return -1;
1889 }
1890 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1891 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001892 _PyUnicode_UTF8(unicode) = NULL;
1893 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001894 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1895 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001896 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001897 PyObject_FREE(_PyUnicode_WSTR(unicode));
1898 _PyUnicode_WSTR(unicode) = NULL;
1899 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1900#else
1901 assert(num_surrogates == 0);
1902
Victor Stinnerc3c74152011-10-02 20:39:55 +02001903 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001904 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001905 _PyUnicode_UTF8(unicode) = NULL;
1906 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1908#endif
1909 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1910 }
1911 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001912 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001913 return 0;
1914}
1915
Alexander Belopolsky40018472011-02-26 01:02:56 +00001916static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001917unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001918{
Walter Dörwald16807132007-05-25 13:52:07 +00001919 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001920 case SSTATE_NOT_INTERNED:
1921 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001922
Benjamin Peterson29060642009-01-31 22:14:21 +00001923 case SSTATE_INTERNED_MORTAL:
1924 /* revive dead object temporarily for DelItem */
Victor Stinnerc86a1122020-02-07 01:24:29 +01001925 Py_SET_REFCNT(unicode, 3);
Victor Stinner607b1022020-05-05 18:50:30 +02001926#ifdef INTERNED_STRINGS
Victor Stinnerec3c99c2020-01-30 12:18:32 +01001927 if (PyDict_DelItem(interned, unicode) != 0) {
1928 _PyErr_WriteUnraisableMsg("deletion of interned string failed",
1929 NULL);
1930 }
Victor Stinner607b1022020-05-05 18:50:30 +02001931#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00001932 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001933
Benjamin Peterson29060642009-01-31 22:14:21 +00001934 case SSTATE_INTERNED_IMMORTAL:
Victor Stinnerec3c99c2020-01-30 12:18:32 +01001935 _PyObject_ASSERT_FAILED_MSG(unicode, "Immortal interned string died");
1936 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001937
Benjamin Peterson29060642009-01-31 22:14:21 +00001938 default:
Victor Stinnerec3c99c2020-01-30 12:18:32 +01001939 Py_UNREACHABLE();
Walter Dörwald16807132007-05-25 13:52:07 +00001940 }
1941
Victor Stinnerec3c99c2020-01-30 12:18:32 +01001942 if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinnerec3c99c2020-01-30 12:18:32 +01001944 }
1945 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001946 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerec3c99c2020-01-30 12:18:32 +01001947 }
1948 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001949 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinnerec3c99c2020-01-30 12:18:32 +01001950 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001951
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001952 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001953}
1954
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001955#ifdef Py_DEBUG
1956static int
1957unicode_is_singleton(PyObject *unicode)
1958{
Victor Stinner607b1022020-05-05 18:50:30 +02001959 if (unicode == unicode_empty) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001960 return 1;
Victor Stinner607b1022020-05-05 18:50:30 +02001961 }
1962#ifdef LATIN1_SINGLETONS
1963 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001964 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1965 {
1966 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1967 if (ch < 256 && unicode_latin1[ch] == unicode)
1968 return 1;
1969 }
Victor Stinner607b1022020-05-05 18:50:30 +02001970#endif
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001971 return 0;
1972}
1973#endif
1974
Alexander Belopolsky40018472011-02-26 01:02:56 +00001975static int
Victor Stinner488fa492011-12-12 00:01:39 +01001976unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001977{
Victor Stinner488fa492011-12-12 00:01:39 +01001978 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001979 if (Py_REFCNT(unicode) != 1)
1980 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001981 if (_PyUnicode_HASH(unicode) != -1)
1982 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001983 if (PyUnicode_CHECK_INTERNED(unicode))
1984 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001985 if (!PyUnicode_CheckExact(unicode))
1986 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001987#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001988 /* singleton refcount is greater than 1 */
1989 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001990#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001991 return 1;
1992}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001993
Victor Stinnerfe226c02011-10-03 03:52:20 +02001994static int
1995unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1996{
1997 PyObject *unicode;
1998 Py_ssize_t old_length;
1999
2000 assert(p_unicode != NULL);
2001 unicode = *p_unicode;
2002
2003 assert(unicode != NULL);
2004 assert(PyUnicode_Check(unicode));
2005 assert(0 <= length);
2006
Victor Stinner910337b2011-10-03 03:20:16 +02002007 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02002008 old_length = PyUnicode_WSTR_LENGTH(unicode);
2009 else
2010 old_length = PyUnicode_GET_LENGTH(unicode);
2011 if (old_length == length)
2012 return 0;
2013
Martin v. Löwise9b11c12011-11-08 17:35:34 +01002014 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02002015 _Py_INCREF_UNICODE_EMPTY();
2016 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00002017 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002018 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01002019 return 0;
2020 }
2021
Victor Stinner488fa492011-12-12 00:01:39 +01002022 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02002023 PyObject *copy = resize_copy(unicode, length);
2024 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002025 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002026 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00002027 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002028 }
2029
Victor Stinnerfe226c02011-10-03 03:52:20 +02002030 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01002031 PyObject *new_unicode = resize_compact(unicode, length);
2032 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02002033 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01002034 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02002035 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04002036 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002037 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002038}
2039
Alexander Belopolsky40018472011-02-26 01:02:56 +00002040int
Victor Stinnerfe226c02011-10-03 03:52:20 +02002041PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00002042{
Victor Stinnerfe226c02011-10-03 03:52:20 +02002043 PyObject *unicode;
2044 if (p_unicode == NULL) {
2045 PyErr_BadInternalCall();
2046 return -1;
2047 }
2048 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01002049 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02002050 {
2051 PyErr_BadInternalCall();
2052 return -1;
2053 }
2054 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00002055}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002056
Serhiy Storchakad65c9492015-11-02 14:10:23 +02002057/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01002058
Victor Stinnerb429d3b2012-02-22 21:22:20 +01002059 WARNING: The function doesn't copy the terminating null character and
2060 doesn't check the maximum character (may write a latin1 character in an
2061 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02002062static void
2063unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
2064 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01002065{
2066 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03002067 const void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02002068 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01002069
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002070 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01002071 switch (kind) {
2072 case PyUnicode_1BYTE_KIND: {
Victor Stinner8c6db452012-10-06 00:40:45 +02002073#ifdef Py_DEBUG
2074 if (PyUnicode_IS_ASCII(unicode)) {
2075 Py_UCS4 maxchar = ucs1lib_find_max_char(
2076 (const Py_UCS1*)str,
2077 (const Py_UCS1*)str + len);
2078 assert(maxchar < 128);
2079 }
2080#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01002081 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02002082 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002083 }
2084 case PyUnicode_2BYTE_KIND: {
2085 Py_UCS2 *start = (Py_UCS2 *)data + index;
2086 Py_UCS2 *ucs2 = start;
Victor Stinnerc5166102012-02-22 13:55:02 +01002087
Victor Stinner184252a2012-06-16 02:57:41 +02002088 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01002089 *ucs2 = (Py_UCS2)*str;
2090
2091 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02002092 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002093 }
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002094 case PyUnicode_4BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01002095 Py_UCS4 *start = (Py_UCS4 *)data + index;
2096 Py_UCS4 *ucs4 = start;
Victor Stinnerc5166102012-02-22 13:55:02 +01002097
Victor Stinner184252a2012-06-16 02:57:41 +02002098 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01002099 *ucs4 = (Py_UCS4)*str;
2100
2101 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002102 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01002103 }
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002104 default:
2105 Py_UNREACHABLE();
Victor Stinnerc5166102012-02-22 13:55:02 +01002106 }
2107}
2108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002109static PyObject*
2110get_latin1_char(unsigned char ch)
2111{
Victor Stinner607b1022020-05-05 18:50:30 +02002112 PyObject *unicode;
2113
2114#ifdef LATIN1_SINGLETONS
2115 unicode = unicode_latin1[ch];
2116 if (unicode) {
2117 Py_INCREF(unicode);
2118 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002119 }
Victor Stinner607b1022020-05-05 18:50:30 +02002120#endif
2121
2122 unicode = PyUnicode_New(1, ch);
2123 if (!unicode) {
2124 return NULL;
2125 }
2126
2127 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
2128 assert(_PyUnicode_CheckConsistency(unicode, 1));
2129
2130#ifdef LATIN1_SINGLETONS
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002131 Py_INCREF(unicode);
Victor Stinner607b1022020-05-05 18:50:30 +02002132 unicode_latin1[ch] = unicode;
2133#endif
Victor Stinnera464fc12011-10-02 20:39:30 +02002134 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002135}
2136
Victor Stinner985a82a2014-01-03 12:53:47 +01002137static PyObject*
2138unicode_char(Py_UCS4 ch)
2139{
2140 PyObject *unicode;
2141
2142 assert(ch <= MAX_UNICODE);
2143
Victor Stinnerf3b46b42014-01-03 13:16:00 +01002144 if (ch < 256)
2145 return get_latin1_char(ch);
2146
Victor Stinner985a82a2014-01-03 12:53:47 +01002147 unicode = PyUnicode_New(1, ch);
2148 if (unicode == NULL)
2149 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002150
2151 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
2152 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01002153 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002154 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01002155 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
2156 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
2157 }
2158 assert(_PyUnicode_CheckConsistency(unicode, 1));
2159 return unicode;
2160}
2161
Alexander Belopolsky40018472011-02-26 01:02:56 +00002162PyObject *
2163PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002164{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002165 if (u == NULL)
2166 return (PyObject*)_PyUnicode_New(size);
2167
2168 if (size < 0) {
2169 PyErr_BadInternalCall();
2170 return NULL;
2171 }
2172
2173 return PyUnicode_FromWideChar(u, size);
2174}
2175
2176PyObject *
2177PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2178{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002179 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002180 Py_UCS4 maxchar = 0;
2181 Py_ssize_t num_surrogates;
2182
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002183 if (u == NULL && size != 0) {
2184 PyErr_BadInternalCall();
2185 return NULL;
2186 }
2187
2188 if (size == -1) {
2189 size = wcslen(u);
2190 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002191
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002192 /* If the Unicode data is known at construction time, we can apply
2193 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002195 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002196 if (size == 0)
2197 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002198
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002199 /* Single character Unicode objects in the Latin-1 range are
2200 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002201 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002202 return get_latin1_char((unsigned char)*u);
2203
2204 /* If not empty and not single character, copy the Unicode data
2205 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002206 if (find_maxchar_surrogates(u, u + size,
2207 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002208 return NULL;
2209
Victor Stinner8faf8212011-12-08 22:14:11 +01002210 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002211 if (!unicode)
2212 return NULL;
2213
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002214 switch (PyUnicode_KIND(unicode)) {
2215 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002216 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2218 break;
2219 case PyUnicode_2BYTE_KIND:
2220#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002221 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002223 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2225#endif
2226 break;
2227 case PyUnicode_4BYTE_KIND:
2228#if SIZEOF_WCHAR_T == 2
2229 /* This is the only case which has to process surrogates, thus
2230 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002231 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232#else
2233 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002234 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002235#endif
2236 break;
2237 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002238 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002239 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002240
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002241 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002242}
2243
Alexander Belopolsky40018472011-02-26 01:02:56 +00002244PyObject *
2245PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002246{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002247 if (size < 0) {
2248 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002249 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002250 return NULL;
2251 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002252 if (u != NULL)
2253 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2254 else
2255 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002256}
2257
Alexander Belopolsky40018472011-02-26 01:02:56 +00002258PyObject *
2259PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002260{
2261 size_t size = strlen(u);
2262 if (size > PY_SSIZE_T_MAX) {
2263 PyErr_SetString(PyExc_OverflowError, "input too long");
2264 return NULL;
2265 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002266 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002267}
2268
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002269PyObject *
2270_PyUnicode_FromId(_Py_Identifier *id)
2271{
2272 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002273 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2274 strlen(id->string),
2275 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002276 if (!id->object)
2277 return NULL;
2278 PyUnicode_InternInPlace(&id->object);
2279 assert(!id->next);
2280 id->next = static_strings;
2281 static_strings = id;
2282 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002283 return id->object;
2284}
2285
Victor Stinnerd6fb53f2020-05-14 01:11:54 +02002286static void
2287unicode_clear_static_strings(void)
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002288{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002289 _Py_Identifier *tmp, *s = static_strings;
2290 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002291 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002292 tmp = s->next;
2293 s->next = NULL;
2294 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002295 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002296 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002297}
2298
Benjamin Peterson0df54292012-03-26 14:50:32 -04002299/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002300
Victor Stinnerd3f08822012-05-29 12:57:52 +02002301PyObject*
2302_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002303{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002304 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002305 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002306 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002307#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002308 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002309#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002310 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002311 }
Victor Stinner785938e2011-12-11 20:09:03 +01002312 unicode = PyUnicode_New(size, 127);
2313 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002314 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002315 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2316 assert(_PyUnicode_CheckConsistency(unicode, 1));
2317 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002318}
2319
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002320static Py_UCS4
2321kind_maxchar_limit(unsigned int kind)
2322{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002323 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002324 case PyUnicode_1BYTE_KIND:
2325 return 0x80;
2326 case PyUnicode_2BYTE_KIND:
2327 return 0x100;
2328 case PyUnicode_4BYTE_KIND:
2329 return 0x10000;
2330 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002331 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002332 }
2333}
2334
Victor Stinner702c7342011-10-05 13:50:52 +02002335static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002336_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002337{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002338 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002339 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002340
Serhiy Storchaka678db842013-01-26 12:16:36 +02002341 if (size == 0)
2342 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002343 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002344 if (size == 1)
2345 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002346
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002347 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002348 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002349 if (!res)
2350 return NULL;
2351 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002352 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002353 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002354}
2355
Victor Stinnere57b1c02011-09-28 22:20:48 +02002356static PyObject*
2357_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002358{
2359 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002360 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002361
Serhiy Storchaka678db842013-01-26 12:16:36 +02002362 if (size == 0)
2363 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002364 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002365 if (size == 1)
2366 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002367
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002368 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002369 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002370 if (!res)
2371 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002372 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002373 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002374 else {
2375 _PyUnicode_CONVERT_BYTES(
2376 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2377 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002378 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 return res;
2380}
2381
Victor Stinnere57b1c02011-09-28 22:20:48 +02002382static PyObject*
2383_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002384{
2385 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002386 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002387
Serhiy Storchaka678db842013-01-26 12:16:36 +02002388 if (size == 0)
2389 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002390 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002391 if (size == 1)
2392 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002393
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002394 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002395 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002396 if (!res)
2397 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002398 if (max_char < 256)
2399 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2400 PyUnicode_1BYTE_DATA(res));
2401 else if (max_char < 0x10000)
2402 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2403 PyUnicode_2BYTE_DATA(res));
2404 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002405 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002406 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002407 return res;
2408}
2409
2410PyObject*
2411PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2412{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002413 if (size < 0) {
2414 PyErr_SetString(PyExc_ValueError, "size must be positive");
2415 return NULL;
2416 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002417 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002419 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002420 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002421 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002422 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002423 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002424 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002425 PyErr_SetString(PyExc_SystemError, "invalid kind");
2426 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002427 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428}
2429
Victor Stinnerece58de2012-04-23 23:36:38 +02002430Py_UCS4
2431_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2432{
2433 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03002434 const void *startptr, *endptr;
Victor Stinnerece58de2012-04-23 23:36:38 +02002435
2436 assert(PyUnicode_IS_READY(unicode));
2437 assert(0 <= start);
2438 assert(end <= PyUnicode_GET_LENGTH(unicode));
2439 assert(start <= end);
2440
2441 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2442 return PyUnicode_MAX_CHAR_VALUE(unicode);
2443
2444 if (start == end)
2445 return 127;
2446
Victor Stinner94d558b2012-04-27 22:26:58 +02002447 if (PyUnicode_IS_ASCII(unicode))
2448 return 127;
2449
Victor Stinnerece58de2012-04-23 23:36:38 +02002450 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002451 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002452 endptr = (char *)startptr + end * kind;
2453 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002454 switch(kind) {
2455 case PyUnicode_1BYTE_KIND:
2456 return ucs1lib_find_max_char(startptr, endptr);
2457 case PyUnicode_2BYTE_KIND:
2458 return ucs2lib_find_max_char(startptr, endptr);
2459 case PyUnicode_4BYTE_KIND:
2460 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002461 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002462 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002463 }
2464}
2465
Victor Stinner25a4b292011-10-06 12:31:55 +02002466/* Ensure that a string uses the most efficient storage, if it is not the
2467 case: create a new string with of the right kind. Write NULL into *p_unicode
2468 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002469static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002470unicode_adjust_maxchar(PyObject **p_unicode)
2471{
2472 PyObject *unicode, *copy;
2473 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002474 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002475 unsigned int kind;
2476
2477 assert(p_unicode != NULL);
2478 unicode = *p_unicode;
2479 assert(PyUnicode_IS_READY(unicode));
2480 if (PyUnicode_IS_ASCII(unicode))
2481 return;
2482
2483 len = PyUnicode_GET_LENGTH(unicode);
2484 kind = PyUnicode_KIND(unicode);
2485 if (kind == PyUnicode_1BYTE_KIND) {
2486 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002487 max_char = ucs1lib_find_max_char(u, u + len);
2488 if (max_char >= 128)
2489 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002490 }
2491 else if (kind == PyUnicode_2BYTE_KIND) {
2492 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002493 max_char = ucs2lib_find_max_char(u, u + len);
2494 if (max_char >= 256)
2495 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002496 }
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002497 else if (kind == PyUnicode_4BYTE_KIND) {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002498 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002499 max_char = ucs4lib_find_max_char(u, u + len);
2500 if (max_char >= 0x10000)
2501 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002502 }
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002503 else
2504 Py_UNREACHABLE();
2505
Victor Stinner25a4b292011-10-06 12:31:55 +02002506 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002507 if (copy != NULL)
2508 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002509 Py_DECREF(unicode);
2510 *p_unicode = copy;
2511}
2512
Victor Stinner034f6cf2011-09-30 02:26:44 +02002513PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002514_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002515{
Victor Stinner87af4f22011-11-21 23:03:47 +01002516 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002517 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002518
Victor Stinner034f6cf2011-09-30 02:26:44 +02002519 if (!PyUnicode_Check(unicode)) {
2520 PyErr_BadInternalCall();
2521 return NULL;
2522 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002523 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002524 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002525
Victor Stinner87af4f22011-11-21 23:03:47 +01002526 length = PyUnicode_GET_LENGTH(unicode);
2527 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002528 if (!copy)
2529 return NULL;
2530 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2531
Christian Heimesf051e432016-09-13 20:22:02 +02002532 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002533 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002534 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002535 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002536}
2537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002538
Victor Stinnerbc603d12011-10-02 01:00:40 +02002539/* Widen Unicode objects to larger buffers. Don't write terminating null
2540 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002541
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002542static void*
2543unicode_askind(unsigned int skind, void const *data, Py_ssize_t len, unsigned int kind)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002544{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002545 void *result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002546
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002547 assert(skind < kind);
Benjamin Petersonead6b532011-12-20 17:23:42 -06002548 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002549 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002550 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002551 if (!result)
2552 return PyErr_NoMemory();
2553 assert(skind == PyUnicode_1BYTE_KIND);
2554 _PyUnicode_CONVERT_BYTES(
2555 Py_UCS1, Py_UCS2,
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002556 (const Py_UCS1 *)data,
2557 ((const Py_UCS1 *)data) + len,
Victor Stinnerbc603d12011-10-02 01:00:40 +02002558 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002560 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002561 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002562 if (!result)
2563 return PyErr_NoMemory();
2564 if (skind == PyUnicode_2BYTE_KIND) {
2565 _PyUnicode_CONVERT_BYTES(
2566 Py_UCS2, Py_UCS4,
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002567 (const Py_UCS2 *)data,
2568 ((const Py_UCS2 *)data) + len,
Victor Stinnerbc603d12011-10-02 01:00:40 +02002569 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002570 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002571 else {
2572 assert(skind == PyUnicode_1BYTE_KIND);
2573 _PyUnicode_CONVERT_BYTES(
2574 Py_UCS1, Py_UCS4,
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002575 (const Py_UCS1 *)data,
2576 ((const Py_UCS1 *)data) + len,
Victor Stinnerbc603d12011-10-02 01:00:40 +02002577 result);
2578 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002579 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002580 default:
Serhiy Storchaka17b47332020-04-01 15:41:49 +03002581 Py_UNREACHABLE();
2582 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002584}
2585
2586static Py_UCS4*
2587as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2588 int copy_null)
2589{
2590 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03002591 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002592 Py_ssize_t len, targetlen;
2593 if (PyUnicode_READY(string) == -1)
2594 return NULL;
2595 kind = PyUnicode_KIND(string);
2596 data = PyUnicode_DATA(string);
2597 len = PyUnicode_GET_LENGTH(string);
2598 targetlen = len;
2599 if (copy_null)
2600 targetlen++;
2601 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002602 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002603 if (!target) {
2604 PyErr_NoMemory();
2605 return NULL;
2606 }
2607 }
2608 else {
2609 if (targetsize < targetlen) {
2610 PyErr_Format(PyExc_SystemError,
2611 "string is longer than the buffer");
2612 if (copy_null && 0 < targetsize)
2613 target[0] = 0;
2614 return NULL;
2615 }
2616 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002617 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03002618 const Py_UCS1 *start = (const Py_UCS1 *) data;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002619 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002621 else if (kind == PyUnicode_2BYTE_KIND) {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03002622 const Py_UCS2 *start = (const Py_UCS2 *) data;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002623 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2624 }
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03002625 else if (kind == PyUnicode_4BYTE_KIND) {
Christian Heimesf051e432016-09-13 20:22:02 +02002626 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002627 }
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03002628 else {
2629 Py_UNREACHABLE();
2630 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002631 if (copy_null)
2632 target[len] = 0;
2633 return target;
2634}
2635
2636Py_UCS4*
2637PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2638 int copy_null)
2639{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002640 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002641 PyErr_BadInternalCall();
2642 return NULL;
2643 }
2644 return as_ucs4(string, target, targetsize, copy_null);
2645}
2646
2647Py_UCS4*
2648PyUnicode_AsUCS4Copy(PyObject *string)
2649{
2650 return as_ucs4(string, NULL, 0, 1);
2651}
2652
Victor Stinner15a11362012-10-06 23:48:20 +02002653/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002654 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2655 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2656#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002657
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002658static int
2659unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2660 Py_ssize_t width, Py_ssize_t precision)
2661{
2662 Py_ssize_t length, fill, arglen;
2663 Py_UCS4 maxchar;
2664
2665 if (PyUnicode_READY(str) == -1)
2666 return -1;
2667
2668 length = PyUnicode_GET_LENGTH(str);
2669 if ((precision == -1 || precision >= length)
2670 && width <= length)
2671 return _PyUnicodeWriter_WriteStr(writer, str);
2672
2673 if (precision != -1)
2674 length = Py_MIN(precision, length);
2675
2676 arglen = Py_MAX(length, width);
2677 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2678 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2679 else
2680 maxchar = writer->maxchar;
2681
2682 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2683 return -1;
2684
2685 if (width > length) {
2686 fill = width - length;
2687 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2688 return -1;
2689 writer->pos += fill;
2690 }
2691
2692 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2693 str, 0, length);
2694 writer->pos += length;
2695 return 0;
2696}
2697
2698static int
Victor Stinner998b8062018-09-12 00:23:25 +02002699unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002700 Py_ssize_t width, Py_ssize_t precision)
2701{
2702 /* UTF-8 */
2703 Py_ssize_t length;
2704 PyObject *unicode;
2705 int res;
2706
Serhiy Storchakad586ccb2019-01-12 10:30:35 +02002707 if (precision == -1) {
2708 length = strlen(str);
2709 }
2710 else {
2711 length = 0;
2712 while (length < precision && str[length]) {
2713 length++;
2714 }
2715 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002716 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2717 if (unicode == NULL)
2718 return -1;
2719
2720 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2721 Py_DECREF(unicode);
2722 return res;
2723}
2724
Victor Stinner96865452011-03-01 23:44:09 +00002725static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002726unicode_fromformat_arg(_PyUnicodeWriter *writer,
2727 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002728{
Victor Stinnere215d962012-10-06 23:03:36 +02002729 const char *p;
2730 Py_ssize_t len;
2731 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002732 Py_ssize_t width;
2733 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002734 int longflag;
2735 int longlongflag;
2736 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002737 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002738
2739 p = f;
2740 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002741 zeropad = 0;
2742 if (*f == '0') {
2743 zeropad = 1;
2744 f++;
2745 }
Victor Stinner96865452011-03-01 23:44:09 +00002746
2747 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002748 width = -1;
2749 if (Py_ISDIGIT((unsigned)*f)) {
2750 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002751 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002752 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002753 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002754 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002755 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002756 return NULL;
2757 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002758 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002759 f++;
2760 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002761 }
2762 precision = -1;
2763 if (*f == '.') {
2764 f++;
2765 if (Py_ISDIGIT((unsigned)*f)) {
2766 precision = (*f - '0');
2767 f++;
2768 while (Py_ISDIGIT((unsigned)*f)) {
2769 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2770 PyErr_SetString(PyExc_ValueError,
2771 "precision too big");
2772 return NULL;
2773 }
2774 precision = (precision * 10) + (*f - '0');
2775 f++;
2776 }
2777 }
Victor Stinner96865452011-03-01 23:44:09 +00002778 if (*f == '%') {
2779 /* "%.3%s" => f points to "3" */
2780 f--;
2781 }
2782 }
2783 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002784 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002785 f--;
2786 }
Victor Stinner96865452011-03-01 23:44:09 +00002787
2788 /* Handle %ld, %lu, %lld and %llu. */
2789 longflag = 0;
2790 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002791 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002792 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002793 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002794 longflag = 1;
2795 ++f;
2796 }
Victor Stinner96865452011-03-01 23:44:09 +00002797 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002798 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002799 longlongflag = 1;
2800 f += 2;
2801 }
Victor Stinner96865452011-03-01 23:44:09 +00002802 }
2803 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002804 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002805 size_tflag = 1;
2806 ++f;
2807 }
Victor Stinnere215d962012-10-06 23:03:36 +02002808
2809 if (f[1] == '\0')
2810 writer->overallocate = 0;
2811
2812 switch (*f) {
2813 case 'c':
2814 {
2815 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002816 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002817 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002818 "character argument not in range(0x110000)");
2819 return NULL;
2820 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002821 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002822 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002823 break;
2824 }
2825
2826 case 'i':
2827 case 'd':
2828 case 'u':
2829 case 'x':
2830 {
2831 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002832 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002833 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002834
2835 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002836 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002837 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002838 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002839 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002840 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002841 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002842 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002843 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002844 va_arg(*vargs, size_t));
2845 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002846 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002847 va_arg(*vargs, unsigned int));
2848 }
2849 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002850 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002851 }
2852 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002853 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002854 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002855 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002856 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002857 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002858 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002859 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002860 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002861 va_arg(*vargs, Py_ssize_t));
2862 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002863 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002864 va_arg(*vargs, int));
2865 }
2866 assert(len >= 0);
2867
Victor Stinnere215d962012-10-06 23:03:36 +02002868 if (precision < len)
2869 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002870
2871 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002872 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2873 return NULL;
2874
Victor Stinnere215d962012-10-06 23:03:36 +02002875 if (width > precision) {
2876 Py_UCS4 fillchar;
2877 fill = width - precision;
2878 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002879 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2880 return NULL;
2881 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002882 }
Victor Stinner15a11362012-10-06 23:48:20 +02002883 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002884 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002885 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2886 return NULL;
2887 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002888 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002889
Victor Stinner4a587072013-11-19 12:54:53 +01002890 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2891 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002892 break;
2893 }
2894
2895 case 'p':
2896 {
2897 char number[MAX_LONG_LONG_CHARS];
2898
2899 len = sprintf(number, "%p", va_arg(*vargs, void*));
2900 assert(len >= 0);
2901
2902 /* %p is ill-defined: ensure leading 0x. */
2903 if (number[1] == 'X')
2904 number[1] = 'x';
2905 else if (number[1] != 'x') {
2906 memmove(number + 2, number,
2907 strlen(number) + 1);
2908 number[0] = '0';
2909 number[1] = 'x';
2910 len += 2;
2911 }
2912
Victor Stinner4a587072013-11-19 12:54:53 +01002913 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002914 return NULL;
2915 break;
2916 }
2917
2918 case 's':
2919 {
2920 /* UTF-8 */
2921 const char *s = va_arg(*vargs, const char*);
Victor Stinner998b8062018-09-12 00:23:25 +02002922 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002923 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002924 break;
2925 }
2926
2927 case 'U':
2928 {
2929 PyObject *obj = va_arg(*vargs, PyObject *);
2930 assert(obj && _PyUnicode_CHECK(obj));
2931
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002932 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002933 return NULL;
2934 break;
2935 }
2936
2937 case 'V':
2938 {
2939 PyObject *obj = va_arg(*vargs, PyObject *);
2940 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002941 if (obj) {
2942 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002943 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002944 return NULL;
2945 }
2946 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002947 assert(str != NULL);
Victor Stinner998b8062018-09-12 00:23:25 +02002948 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002949 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002950 }
2951 break;
2952 }
2953
2954 case 'S':
2955 {
2956 PyObject *obj = va_arg(*vargs, PyObject *);
2957 PyObject *str;
2958 assert(obj);
2959 str = PyObject_Str(obj);
2960 if (!str)
2961 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002962 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002963 Py_DECREF(str);
2964 return NULL;
2965 }
2966 Py_DECREF(str);
2967 break;
2968 }
2969
2970 case 'R':
2971 {
2972 PyObject *obj = va_arg(*vargs, PyObject *);
2973 PyObject *repr;
2974 assert(obj);
2975 repr = PyObject_Repr(obj);
2976 if (!repr)
2977 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002978 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002979 Py_DECREF(repr);
2980 return NULL;
2981 }
2982 Py_DECREF(repr);
2983 break;
2984 }
2985
2986 case 'A':
2987 {
2988 PyObject *obj = va_arg(*vargs, PyObject *);
2989 PyObject *ascii;
2990 assert(obj);
2991 ascii = PyObject_ASCII(obj);
2992 if (!ascii)
2993 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002994 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002995 Py_DECREF(ascii);
2996 return NULL;
2997 }
2998 Py_DECREF(ascii);
2999 break;
3000 }
3001
3002 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02003003 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02003004 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02003005 break;
3006
3007 default:
3008 /* if we stumble upon an unknown formatting code, copy the rest
3009 of the format string to the output string. (we cannot just
3010 skip the code, since there's no way to know what's in the
3011 argument list) */
3012 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01003013 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02003014 return NULL;
3015 f = p+len;
3016 return f;
3017 }
3018
3019 f++;
Victor Stinner96865452011-03-01 23:44:09 +00003020 return f;
3021}
3022
Walter Dörwaldd2034312007-05-18 16:29:38 +00003023PyObject *
3024PyUnicode_FromFormatV(const char *format, va_list vargs)
3025{
Victor Stinnere215d962012-10-06 23:03:36 +02003026 va_list vargs2;
3027 const char *f;
3028 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003029
Victor Stinner8f674cc2013-04-17 23:02:17 +02003030 _PyUnicodeWriter_Init(&writer);
3031 writer.min_length = strlen(format) + 100;
3032 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02003033
Benjamin Peterson0c212142016-09-20 20:39:33 -07003034 // Copy varags to be able to pass a reference to a subfunction.
3035 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02003036
3037 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00003038 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02003039 f = unicode_fromformat_arg(&writer, f, &vargs2);
3040 if (f == NULL)
3041 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00003042 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003043 else {
Victor Stinnere215d962012-10-06 23:03:36 +02003044 const char *p;
3045 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003046
Victor Stinnere215d962012-10-06 23:03:36 +02003047 p = f;
3048 do
3049 {
3050 if ((unsigned char)*p > 127) {
3051 PyErr_Format(PyExc_ValueError,
3052 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
3053 "string, got a non-ASCII byte: 0x%02x",
3054 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02003055 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02003056 }
3057 p++;
3058 }
3059 while (*p != '\0' && *p != '%');
3060 len = p - f;
3061
3062 if (*p == '\0')
3063 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01003064
3065 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02003066 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02003067
3068 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003069 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00003070 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02003071 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02003072 return _PyUnicodeWriter_Finish(&writer);
3073
3074 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02003075 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02003076 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00003077 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003078}
3079
Walter Dörwaldd2034312007-05-18 16:29:38 +00003080PyObject *
3081PyUnicode_FromFormat(const char *format, ...)
3082{
Benjamin Peterson14339b62009-01-31 16:36:08 +00003083 PyObject* ret;
3084 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003085
3086#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00003087 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00003088#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00003089 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00003090#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00003091 ret = PyUnicode_FromFormatV(format, vargs);
3092 va_end(vargs);
3093 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00003094}
3095
Serhiy Storchakac46db922018-10-23 22:58:24 +03003096static Py_ssize_t
3097unicode_get_widechar_size(PyObject *unicode)
3098{
3099 Py_ssize_t res;
3100
3101 assert(unicode != NULL);
3102 assert(_PyUnicode_CHECK(unicode));
3103
3104 if (_PyUnicode_WSTR(unicode) != NULL) {
3105 return PyUnicode_WSTR_LENGTH(unicode);
3106 }
3107 assert(PyUnicode_IS_READY(unicode));
3108
3109 res = _PyUnicode_LENGTH(unicode);
3110#if SIZEOF_WCHAR_T == 2
3111 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
3112 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3113 const Py_UCS4 *end = s + res;
3114 for (; s < end; ++s) {
3115 if (*s > 0xFFFF) {
3116 ++res;
3117 }
3118 }
3119 }
3120#endif
3121 return res;
3122}
3123
3124static void
3125unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3126{
3127 const wchar_t *wstr;
3128
3129 assert(unicode != NULL);
3130 assert(_PyUnicode_CHECK(unicode));
3131
3132 wstr = _PyUnicode_WSTR(unicode);
3133 if (wstr != NULL) {
3134 memcpy(w, wstr, size * sizeof(wchar_t));
3135 return;
3136 }
3137 assert(PyUnicode_IS_READY(unicode));
3138
3139 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3140 const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3141 for (; size--; ++s, ++w) {
3142 *w = *s;
3143 }
3144 }
3145 else {
3146#if SIZEOF_WCHAR_T == 4
3147 assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3148 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3149 for (; size--; ++s, ++w) {
3150 *w = *s;
3151 }
3152#else
3153 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
3154 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3155 for (; size--; ++s, ++w) {
3156 Py_UCS4 ch = *s;
3157 if (ch > 0xFFFF) {
3158 assert(ch <= MAX_UNICODE);
3159 /* encode surrogate pair in this case */
3160 *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
3161 if (!size--)
3162 break;
3163 *w = Py_UNICODE_LOW_SURROGATE(ch);
3164 }
3165 else {
3166 *w = ch;
3167 }
3168 }
3169#endif
3170 }
3171}
3172
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003173#ifdef HAVE_WCHAR_H
3174
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003175/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00003176
Victor Stinnerd88d9832011-09-06 02:00:05 +02003177 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003178 character) required to convert the unicode object. Ignore size argument.
3179
Victor Stinnerd88d9832011-09-06 02:00:05 +02003180 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003181 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02003182 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003183Py_ssize_t
3184PyUnicode_AsWideChar(PyObject *unicode,
3185 wchar_t *w,
3186 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00003187{
Victor Stinner5593d8a2010-10-02 11:11:27 +00003188 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003189
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003190 if (unicode == NULL) {
3191 PyErr_BadInternalCall();
3192 return -1;
3193 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003194 if (!PyUnicode_Check(unicode)) {
3195 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003196 return -1;
Victor Stinner5593d8a2010-10-02 11:11:27 +00003197 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003198
3199 res = unicode_get_widechar_size(unicode);
3200 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003201 return res + 1;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003202 }
3203
3204 if (size > res) {
3205 size = res + 1;
3206 }
3207 else {
3208 res = size;
3209 }
3210 unicode_copy_as_widechar(unicode, w, size);
3211 return res;
Victor Stinner137c34c2010-09-29 10:25:54 +00003212}
3213
Victor Stinner137c34c2010-09-29 10:25:54 +00003214wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003215PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00003216 Py_ssize_t *size)
3217{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003218 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00003219 Py_ssize_t buflen;
3220
3221 if (unicode == NULL) {
3222 PyErr_BadInternalCall();
3223 return NULL;
3224 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003225 if (!PyUnicode_Check(unicode)) {
3226 PyErr_BadArgument();
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003227 return NULL;
3228 }
3229
Serhiy Storchakac46db922018-10-23 22:58:24 +03003230 buflen = unicode_get_widechar_size(unicode);
3231 buffer = (wchar_t *) PyMem_NEW(wchar_t, (buflen + 1));
Victor Stinner137c34c2010-09-29 10:25:54 +00003232 if (buffer == NULL) {
3233 PyErr_NoMemory();
3234 return NULL;
3235 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003236 unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3237 if (size != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00003238 *size = buflen;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003239 }
3240 else if (wcslen(buffer) != (size_t)buflen) {
3241 PyMem_FREE(buffer);
3242 PyErr_SetString(PyExc_ValueError,
3243 "embedded null character");
3244 return NULL;
3245 }
Victor Stinner137c34c2010-09-29 10:25:54 +00003246 return buffer;
3247}
3248
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003249#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003250
Alexander Belopolsky40018472011-02-26 01:02:56 +00003251PyObject *
3252PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003253{
Victor Stinner8faf8212011-12-08 22:14:11 +01003254 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003255 PyErr_SetString(PyExc_ValueError,
3256 "chr() arg not in range(0x110000)");
3257 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003258 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003259
Victor Stinner985a82a2014-01-03 12:53:47 +01003260 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003261}
3262
Alexander Belopolsky40018472011-02-26 01:02:56 +00003263PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003264PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003265{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003266 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003267 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003268 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003269 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003270 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003271 Py_INCREF(obj);
3272 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003273 }
3274 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003275 /* For a Unicode subtype that's not a Unicode object,
3276 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003277 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003278 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003279 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003280 "Can't convert '%.100s' object to str implicitly",
3281 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003282 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003283}
3284
Alexander Belopolsky40018472011-02-26 01:02:56 +00003285PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003286PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003287 const char *encoding,
3288 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003289{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003290 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003291 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003292
Guido van Rossumd57fd912000-03-10 22:53:23 +00003293 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003294 PyErr_BadInternalCall();
3295 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003296 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003297
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003298 /* Decoding bytes objects is the most common case and should be fast */
3299 if (PyBytes_Check(obj)) {
Victor Stinner22eb6892019-06-26 00:51:05 +02003300 if (PyBytes_GET_SIZE(obj) == 0) {
3301 if (unicode_check_encoding_errors(encoding, errors) < 0) {
3302 return NULL;
3303 }
Serhiy Storchaka05997252013-01-26 12:14:02 +02003304 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner22eb6892019-06-26 00:51:05 +02003305 }
3306 return PyUnicode_Decode(
Serhiy Storchaka05997252013-01-26 12:14:02 +02003307 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3308 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003309 }
3310
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003311 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003312 PyErr_SetString(PyExc_TypeError,
3313 "decoding str is not supported");
3314 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003315 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003316
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003317 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3318 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3319 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003320 "decoding to str: need a bytes-like object, %.80s found",
3321 Py_TYPE(obj)->tp_name);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003322 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003323 }
Tim Petersced69f82003-09-16 20:30:58 +00003324
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003325 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003326 PyBuffer_Release(&buffer);
Victor Stinner22eb6892019-06-26 00:51:05 +02003327 if (unicode_check_encoding_errors(encoding, errors) < 0) {
3328 return NULL;
3329 }
Serhiy Storchaka05997252013-01-26 12:14:02 +02003330 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003331 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003332
Serhiy Storchaka05997252013-01-26 12:14:02 +02003333 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003334 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003335 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003336}
3337
Victor Stinnerebe17e02016-10-12 13:57:45 +02003338/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3339 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3340 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003341int
3342_Py_normalize_encoding(const char *encoding,
3343 char *lower,
3344 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003345{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003346 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003347 char *l;
3348 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003349 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003350
Victor Stinner942889a2016-09-05 15:40:10 -07003351 assert(encoding != NULL);
3352
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003353 e = encoding;
3354 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003355 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003356 punct = 0;
3357 while (1) {
3358 char c = *e;
3359 if (c == 0) {
3360 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003361 }
Victor Stinner942889a2016-09-05 15:40:10 -07003362
3363 if (Py_ISALNUM(c) || c == '.') {
3364 if (punct && l != lower) {
3365 if (l == l_end) {
3366 return 0;
3367 }
3368 *l++ = '_';
3369 }
3370 punct = 0;
3371
3372 if (l == l_end) {
3373 return 0;
3374 }
3375 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003376 }
3377 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003378 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003379 }
Victor Stinner942889a2016-09-05 15:40:10 -07003380
3381 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003382 }
3383 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003384 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003385}
3386
Alexander Belopolsky40018472011-02-26 01:02:56 +00003387PyObject *
3388PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003389 Py_ssize_t size,
3390 const char *encoding,
3391 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003392{
3393 PyObject *buffer = NULL, *unicode;
3394 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003395 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3396
Victor Stinner22eb6892019-06-26 00:51:05 +02003397 if (unicode_check_encoding_errors(encoding, errors) < 0) {
3398 return NULL;
3399 }
3400
Victor Stinnered076ed2019-06-26 01:49:32 +02003401 if (size == 0) {
3402 _Py_RETURN_UNICODE_EMPTY();
3403 }
3404
Victor Stinner942889a2016-09-05 15:40:10 -07003405 if (encoding == NULL) {
3406 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3407 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003408
Fred Drakee4315f52000-05-09 19:53:39 +00003409 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003410 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3411 char *lower = buflower;
3412
3413 /* Fast paths */
3414 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3415 lower += 3;
3416 if (*lower == '_') {
3417 /* Match "utf8" and "utf_8" */
3418 lower++;
3419 }
3420
3421 if (lower[0] == '8' && lower[1] == 0) {
3422 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3423 }
3424 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3425 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3426 }
3427 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3428 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3429 }
3430 }
3431 else {
3432 if (strcmp(lower, "ascii") == 0
3433 || strcmp(lower, "us_ascii") == 0) {
3434 return PyUnicode_DecodeASCII(s, size, errors);
3435 }
Steve Dowercc16be82016-09-08 10:35:16 -07003436 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003437 else if (strcmp(lower, "mbcs") == 0) {
3438 return PyUnicode_DecodeMBCS(s, size, errors);
3439 }
3440 #endif
3441 else if (strcmp(lower, "latin1") == 0
3442 || strcmp(lower, "latin_1") == 0
3443 || strcmp(lower, "iso_8859_1") == 0
3444 || strcmp(lower, "iso8859_1") == 0) {
3445 return PyUnicode_DecodeLatin1(s, size, errors);
3446 }
3447 }
Victor Stinner37296e82010-06-10 13:36:23 +00003448 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003449
3450 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003451 buffer = NULL;
Benjamin Peterson95905ce2020-02-11 19:36:14 -08003452 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003453 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003454 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003455 if (buffer == NULL)
3456 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003457 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003458 if (unicode == NULL)
3459 goto onError;
3460 if (!PyUnicode_Check(unicode)) {
3461 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003462 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003463 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003464 encoding,
3465 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003466 Py_DECREF(unicode);
3467 goto onError;
3468 }
3469 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003470 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003471
Benjamin Peterson29060642009-01-31 22:14:21 +00003472 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003473 Py_XDECREF(buffer);
3474 return NULL;
3475}
3476
Alexander Belopolsky40018472011-02-26 01:02:56 +00003477PyObject *
3478PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003479 const char *encoding,
3480 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003481{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003482 if (!PyUnicode_Check(unicode)) {
3483 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003484 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003485 }
3486
Serhiy Storchaka00939072016-10-27 21:05:49 +03003487 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3488 "PyUnicode_AsDecodedObject() is deprecated; "
3489 "use PyCodec_Decode() to decode from str", 1) < 0)
3490 return NULL;
3491
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003492 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003493 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003494
3495 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003496 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003497}
3498
Alexander Belopolsky40018472011-02-26 01:02:56 +00003499PyObject *
3500PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003501 const char *encoding,
3502 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003503{
3504 PyObject *v;
3505
3506 if (!PyUnicode_Check(unicode)) {
3507 PyErr_BadArgument();
3508 goto onError;
3509 }
3510
Serhiy Storchaka00939072016-10-27 21:05:49 +03003511 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3512 "PyUnicode_AsDecodedUnicode() is deprecated; "
3513 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3514 return NULL;
3515
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003516 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003517 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003518
3519 /* Decode via the codec registry */
3520 v = PyCodec_Decode(unicode, encoding, errors);
3521 if (v == NULL)
3522 goto onError;
3523 if (!PyUnicode_Check(v)) {
3524 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003525 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003526 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003527 encoding,
3528 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003529 Py_DECREF(v);
3530 goto onError;
3531 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003532 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003533
Benjamin Peterson29060642009-01-31 22:14:21 +00003534 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003535 return NULL;
3536}
3537
Alexander Belopolsky40018472011-02-26 01:02:56 +00003538PyObject *
3539PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003540 Py_ssize_t size,
3541 const char *encoding,
3542 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003543{
3544 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003545
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003546 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003547 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003548 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003549 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3550 Py_DECREF(unicode);
3551 return v;
3552}
3553
Alexander Belopolsky40018472011-02-26 01:02:56 +00003554PyObject *
3555PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003556 const char *encoding,
3557 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003558{
3559 PyObject *v;
3560
3561 if (!PyUnicode_Check(unicode)) {
3562 PyErr_BadArgument();
3563 goto onError;
3564 }
3565
Serhiy Storchaka00939072016-10-27 21:05:49 +03003566 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3567 "PyUnicode_AsEncodedObject() is deprecated; "
3568 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3569 "or PyCodec_Encode() for generic encoding", 1) < 0)
3570 return NULL;
3571
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003572 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003573 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003574
3575 /* Encode via the codec registry */
3576 v = PyCodec_Encode(unicode, encoding, errors);
3577 if (v == NULL)
3578 goto onError;
3579 return v;
3580
Benjamin Peterson29060642009-01-31 22:14:21 +00003581 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003582 return NULL;
3583}
3584
Victor Stinner1b579672011-12-17 05:47:23 +01003585
Victor Stinner2cba6b82018-01-10 22:46:15 +01003586static PyObject *
Victor Stinner709d23d2019-05-02 14:56:30 -04003587unicode_encode_locale(PyObject *unicode, _Py_error_handler error_handler,
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003588 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003589{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003590 Py_ssize_t wlen;
3591 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3592 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003593 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003594 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003595
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003596 if ((size_t)wlen != wcslen(wstr)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003597 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003598 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003599 return NULL;
3600 }
3601
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003602 char *str;
3603 size_t error_pos;
3604 const char *reason;
3605 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003606 current_locale, error_handler);
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003607 PyMem_Free(wstr);
3608
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003609 if (res != 0) {
3610 if (res == -2) {
3611 PyObject *exc;
3612 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3613 "locale", unicode,
3614 (Py_ssize_t)error_pos,
3615 (Py_ssize_t)(error_pos+1),
3616 reason);
3617 if (exc != NULL) {
3618 PyCodec_StrictErrors(exc);
3619 Py_DECREF(exc);
3620 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003621 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003622 else if (res == -3) {
3623 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3624 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003625 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003626 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003627 }
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003628 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003629 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003630
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003631 PyObject *bytes = PyBytes_FromString(str);
3632 PyMem_RawFree(str);
3633 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003634}
3635
Victor Stinnerad158722010-10-27 00:25:46 +00003636PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003637PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3638{
Victor Stinner709d23d2019-05-02 14:56:30 -04003639 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3640 return unicode_encode_locale(unicode, error_handler, 1);
Victor Stinner2cba6b82018-01-10 22:46:15 +01003641}
3642
3643PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003644PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003645{
Victor Stinner81a7be32020-04-14 15:14:01 +02003646 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinner3d17c042020-05-14 01:48:38 +02003647 struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3648 if (fs_codec->utf8) {
Victor Stinner709d23d2019-05-02 14:56:30 -04003649 return unicode_encode_utf8(unicode,
Victor Stinner3d17c042020-05-14 01:48:38 +02003650 fs_codec->error_handler,
3651 fs_codec->errors);
Victor Stinner709d23d2019-05-02 14:56:30 -04003652 }
Victor Stinnerbf305cc2020-02-05 17:39:57 +01003653#ifndef _Py_FORCE_UTF8_FS_ENCODING
Victor Stinner3d17c042020-05-14 01:48:38 +02003654 else if (fs_codec->encoding) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003655 return PyUnicode_AsEncodedString(unicode,
Victor Stinner3d17c042020-05-14 01:48:38 +02003656 fs_codec->encoding,
3657 fs_codec->errors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003658 }
Victor Stinnerad158722010-10-27 00:25:46 +00003659#endif
Victor Stinnerbf305cc2020-02-05 17:39:57 +01003660 else {
3661 /* Before _PyUnicode_InitEncodings() is called, the Python codec
3662 machinery is not ready and so cannot be used:
3663 use wcstombs() in this case. */
Victor Stinnerda7933e2020-04-13 03:04:28 +02003664 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3665 const wchar_t *filesystem_errors = config->filesystem_errors;
Victor Stinnerbf305cc2020-02-05 17:39:57 +01003666 assert(filesystem_errors != NULL);
3667 _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3668 assert(errors != _Py_ERROR_UNKNOWN);
3669#ifdef _Py_FORCE_UTF8_FS_ENCODING
3670 return unicode_encode_utf8(unicode, errors, NULL);
3671#else
3672 return unicode_encode_locale(unicode, errors, 0);
3673#endif
3674 }
Victor Stinnerae6265f2010-05-15 16:27:27 +00003675}
3676
Alexander Belopolsky40018472011-02-26 01:02:56 +00003677PyObject *
3678PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003679 const char *encoding,
3680 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003681{
3682 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003683 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003684
Guido van Rossumd57fd912000-03-10 22:53:23 +00003685 if (!PyUnicode_Check(unicode)) {
3686 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003687 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003688 }
Fred Drakee4315f52000-05-09 19:53:39 +00003689
Victor Stinner22eb6892019-06-26 00:51:05 +02003690 if (unicode_check_encoding_errors(encoding, errors) < 0) {
3691 return NULL;
3692 }
3693
Victor Stinner942889a2016-09-05 15:40:10 -07003694 if (encoding == NULL) {
3695 return _PyUnicode_AsUTF8String(unicode, errors);
3696 }
3697
Fred Drakee4315f52000-05-09 19:53:39 +00003698 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003699 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3700 char *lower = buflower;
3701
3702 /* Fast paths */
3703 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3704 lower += 3;
3705 if (*lower == '_') {
3706 /* Match "utf8" and "utf_8" */
3707 lower++;
3708 }
3709
3710 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003711 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003712 }
3713 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3714 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3715 }
3716 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3717 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3718 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003719 }
Victor Stinner942889a2016-09-05 15:40:10 -07003720 else {
3721 if (strcmp(lower, "ascii") == 0
3722 || strcmp(lower, "us_ascii") == 0) {
3723 return _PyUnicode_AsASCIIString(unicode, errors);
3724 }
Steve Dowercc16be82016-09-08 10:35:16 -07003725#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003726 else if (strcmp(lower, "mbcs") == 0) {
3727 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3728 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003729#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003730 else if (strcmp(lower, "latin1") == 0 ||
3731 strcmp(lower, "latin_1") == 0 ||
3732 strcmp(lower, "iso_8859_1") == 0 ||
3733 strcmp(lower, "iso8859_1") == 0) {
3734 return _PyUnicode_AsLatin1String(unicode, errors);
3735 }
3736 }
Victor Stinner37296e82010-06-10 13:36:23 +00003737 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003738
3739 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003740 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003741 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003742 return NULL;
3743
3744 /* The normal path */
3745 if (PyBytes_Check(v))
3746 return v;
3747
3748 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003749 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003750 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003751 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003752
3753 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003754 "encoder %s returned bytearray instead of bytes; "
3755 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003756 encoding);
3757 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003758 Py_DECREF(v);
3759 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003760 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003761
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003762 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3763 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003764 Py_DECREF(v);
3765 return b;
3766 }
3767
3768 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003769 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003770 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003771 encoding,
3772 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003773 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003774 return NULL;
3775}
3776
Alexander Belopolsky40018472011-02-26 01:02:56 +00003777PyObject *
3778PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003779 const char *encoding,
3780 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003781{
3782 PyObject *v;
3783
3784 if (!PyUnicode_Check(unicode)) {
3785 PyErr_BadArgument();
3786 goto onError;
3787 }
3788
Serhiy Storchaka00939072016-10-27 21:05:49 +03003789 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3790 "PyUnicode_AsEncodedUnicode() is deprecated; "
3791 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3792 return NULL;
3793
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003794 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003795 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003796
3797 /* Encode via the codec registry */
3798 v = PyCodec_Encode(unicode, encoding, errors);
3799 if (v == NULL)
3800 goto onError;
3801 if (!PyUnicode_Check(v)) {
3802 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003803 "'%.400s' encoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003804 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003805 encoding,
3806 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003807 Py_DECREF(v);
3808 goto onError;
3809 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003810 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003811
Benjamin Peterson29060642009-01-31 22:14:21 +00003812 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003813 return NULL;
3814}
3815
Victor Stinner2cba6b82018-01-10 22:46:15 +01003816static PyObject*
Victor Stinner709d23d2019-05-02 14:56:30 -04003817unicode_decode_locale(const char *str, Py_ssize_t len,
3818 _Py_error_handler errors, int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003819{
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003820 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3821 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003822 return NULL;
3823 }
3824
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003825 wchar_t *wstr;
3826 size_t wlen;
3827 const char *reason;
3828 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
Victor Stinner709d23d2019-05-02 14:56:30 -04003829 current_locale, errors);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003830 if (res != 0) {
3831 if (res == -2) {
3832 PyObject *exc;
3833 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3834 "locale", str, len,
3835 (Py_ssize_t)wlen,
3836 (Py_ssize_t)(wlen + 1),
3837 reason);
3838 if (exc != NULL) {
3839 PyCodec_StrictErrors(exc);
3840 Py_DECREF(exc);
3841 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003842 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003843 else if (res == -3) {
3844 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3845 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003846 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003847 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003848 }
Victor Stinner2f197072011-12-17 07:08:30 +01003849 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003850 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003851
3852 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3853 PyMem_RawFree(wstr);
3854 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003855}
3856
3857PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003858PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3859 const char *errors)
3860{
Victor Stinner709d23d2019-05-02 14:56:30 -04003861 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3862 return unicode_decode_locale(str, len, error_handler, 1);
Victor Stinner2cba6b82018-01-10 22:46:15 +01003863}
3864
3865PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003866PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003867{
3868 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner709d23d2019-05-02 14:56:30 -04003869 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
3870 return unicode_decode_locale(str, size, error_handler, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003871}
3872
3873
3874PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003875PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003876 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003877 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3878}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003879
Christian Heimes5894ba72007-11-04 11:43:14 +00003880PyObject*
3881PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3882{
Victor Stinner81a7be32020-04-14 15:14:01 +02003883 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinner3d17c042020-05-14 01:48:38 +02003884 struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
3885 if (fs_codec->utf8) {
Victor Stinner709d23d2019-05-02 14:56:30 -04003886 return unicode_decode_utf8(s, size,
Victor Stinner3d17c042020-05-14 01:48:38 +02003887 fs_codec->error_handler,
3888 fs_codec->errors,
Victor Stinner709d23d2019-05-02 14:56:30 -04003889 NULL);
3890 }
Victor Stinnerbf305cc2020-02-05 17:39:57 +01003891#ifndef _Py_FORCE_UTF8_FS_ENCODING
Victor Stinner3d17c042020-05-14 01:48:38 +02003892 else if (fs_codec->encoding) {
Steve Dower78057b42016-11-06 19:35:08 -08003893 return PyUnicode_Decode(s, size,
Victor Stinner3d17c042020-05-14 01:48:38 +02003894 fs_codec->encoding,
3895 fs_codec->errors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003896 }
Victor Stinnerad158722010-10-27 00:25:46 +00003897#endif
Victor Stinnerbf305cc2020-02-05 17:39:57 +01003898 else {
3899 /* Before _PyUnicode_InitEncodings() is called, the Python codec
3900 machinery is not ready and so cannot be used:
3901 use mbstowcs() in this case. */
Victor Stinnerda7933e2020-04-13 03:04:28 +02003902 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3903 const wchar_t *filesystem_errors = config->filesystem_errors;
Victor Stinnerbf305cc2020-02-05 17:39:57 +01003904 assert(filesystem_errors != NULL);
3905 _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
3906 assert(errors != _Py_ERROR_UNKNOWN);
3907#ifdef _Py_FORCE_UTF8_FS_ENCODING
3908 return unicode_decode_utf8(s, size, errors, NULL, NULL);
3909#else
3910 return unicode_decode_locale(s, size, errors, 0);
3911#endif
3912 }
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003913}
3914
Martin v. Löwis011e8422009-05-05 04:43:17 +00003915
3916int
3917PyUnicode_FSConverter(PyObject* arg, void* addr)
3918{
Brett Cannonec6ce872016-09-06 15:50:29 -07003919 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003920 PyObject *output = NULL;
3921 Py_ssize_t size;
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003922 const char *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003923 if (arg == NULL) {
3924 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003925 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003926 return 1;
3927 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003928 path = PyOS_FSPath(arg);
3929 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003930 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003931 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003932 if (PyBytes_Check(path)) {
3933 output = path;
3934 }
3935 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3936 output = PyUnicode_EncodeFSDefault(path);
3937 Py_DECREF(path);
3938 if (!output) {
3939 return 0;
3940 }
3941 assert(PyBytes_Check(output));
3942 }
3943
Victor Stinner0ea2a462010-04-30 00:22:08 +00003944 size = PyBytes_GET_SIZE(output);
3945 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003946 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003947 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003948 Py_DECREF(output);
3949 return 0;
3950 }
3951 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003952 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003953}
3954
3955
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003956int
3957PyUnicode_FSDecoder(PyObject* arg, void* addr)
3958{
Brett Cannona5711202016-09-06 19:36:01 -07003959 int is_buffer = 0;
3960 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003961 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003962 if (arg == NULL) {
3963 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003964 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003965 return 1;
3966 }
Brett Cannona5711202016-09-06 19:36:01 -07003967
3968 is_buffer = PyObject_CheckBuffer(arg);
3969 if (!is_buffer) {
3970 path = PyOS_FSPath(arg);
3971 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003972 return 0;
3973 }
Brett Cannona5711202016-09-06 19:36:01 -07003974 }
3975 else {
3976 path = arg;
3977 Py_INCREF(arg);
3978 }
3979
3980 if (PyUnicode_Check(path)) {
Brett Cannona5711202016-09-06 19:36:01 -07003981 output = path;
3982 }
3983 else if (PyBytes_Check(path) || is_buffer) {
3984 PyObject *path_bytes = NULL;
3985
3986 if (!PyBytes_Check(path) &&
3987 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Victor Stinner998b8062018-09-12 00:23:25 +02003988 "path should be string, bytes, or os.PathLike, not %.200s",
3989 Py_TYPE(arg)->tp_name)) {
3990 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003991 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003992 }
3993 path_bytes = PyBytes_FromObject(path);
3994 Py_DECREF(path);
3995 if (!path_bytes) {
3996 return 0;
3997 }
3998 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3999 PyBytes_GET_SIZE(path_bytes));
4000 Py_DECREF(path_bytes);
4001 if (!output) {
4002 return 0;
4003 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00004004 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03004005 else {
4006 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02004007 "path should be string, bytes, or os.PathLike, not %.200s",
4008 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07004009 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03004010 return 0;
4011 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05004012 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02004013 Py_DECREF(output);
4014 return 0;
4015 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004016 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02004017 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03004018 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00004019 Py_DECREF(output);
4020 return 0;
4021 }
4022 *(PyObject**)addr = output;
4023 return Py_CLEANUP_SUPPORTED;
4024}
4025
4026
Inada Naoki02a4d572020-02-27 13:48:59 +09004027static int unicode_fill_utf8(PyObject *unicode);
4028
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02004029const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004030PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00004031{
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00004032 if (!PyUnicode_Check(unicode)) {
4033 PyErr_BadArgument();
4034 return NULL;
4035 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004036 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00004037 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004038
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004039 if (PyUnicode_UTF8(unicode) == NULL) {
Inada Naoki02a4d572020-02-27 13:48:59 +09004040 if (unicode_fill_utf8(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004041 return NULL;
4042 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004043 }
4044
4045 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004046 *psize = PyUnicode_UTF8_LENGTH(unicode);
4047 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004048}
4049
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02004050const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004051PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00004052{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004053 return PyUnicode_AsUTF8AndSize(unicode, NULL);
4054}
4055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004056Py_UNICODE *
4057PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
4058{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004059 if (!PyUnicode_Check(unicode)) {
4060 PyErr_BadArgument();
4061 return NULL;
4062 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03004063 Py_UNICODE *w = _PyUnicode_WSTR(unicode);
4064 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004065 /* Non-ASCII compact unicode object */
Serhiy Storchakac46db922018-10-23 22:58:24 +03004066 assert(_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004067 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004068
Serhiy Storchakac46db922018-10-23 22:58:24 +03004069 Py_ssize_t wlen = unicode_get_widechar_size(unicode);
4070 if ((size_t)wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
4071 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004072 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004073 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03004074 w = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) * (wlen + 1));
4075 if (w == NULL) {
4076 PyErr_NoMemory();
4077 return NULL;
4078 }
4079 unicode_copy_as_widechar(unicode, w, wlen + 1);
4080 _PyUnicode_WSTR(unicode) = w;
4081 if (!PyUnicode_IS_COMPACT_ASCII(unicode)) {
4082 _PyUnicode_WSTR_LENGTH(unicode) = wlen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004083 }
4084 }
4085 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02004086 *size = PyUnicode_WSTR_LENGTH(unicode);
Serhiy Storchakac46db922018-10-23 22:58:24 +03004087 return w;
Martin v. Löwis5b222132007-06-10 09:51:05 +00004088}
4089
Alexander Belopolsky40018472011-02-26 01:02:56 +00004090Py_UNICODE *
4091PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004092{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004093 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004094}
4095
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03004096const Py_UNICODE *
4097_PyUnicode_AsUnicode(PyObject *unicode)
4098{
4099 Py_ssize_t size;
4100 const Py_UNICODE *wstr;
4101
4102 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
4103 if (wstr && wcslen(wstr) != (size_t)size) {
4104 PyErr_SetString(PyExc_ValueError, "embedded null character");
4105 return NULL;
4106 }
4107 return wstr;
4108}
4109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004110
Alexander Belopolsky40018472011-02-26 01:02:56 +00004111Py_ssize_t
4112PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004113{
4114 if (!PyUnicode_Check(unicode)) {
4115 PyErr_BadArgument();
4116 goto onError;
4117 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004118 if (_PyUnicode_WSTR(unicode) == NULL) {
4119 if (PyUnicode_AsUnicode(unicode) == NULL)
4120 goto onError;
4121 }
4122 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004123
Benjamin Peterson29060642009-01-31 22:14:21 +00004124 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00004125 return -1;
4126}
4127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004128Py_ssize_t
4129PyUnicode_GetLength(PyObject *unicode)
4130{
Victor Stinner07621332012-06-16 04:53:46 +02004131 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004132 PyErr_BadArgument();
4133 return -1;
4134 }
Victor Stinner07621332012-06-16 04:53:46 +02004135 if (PyUnicode_READY(unicode) == -1)
4136 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004137 return PyUnicode_GET_LENGTH(unicode);
4138}
4139
4140Py_UCS4
4141PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
4142{
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03004143 const void *data;
Victor Stinner69ed0f42013-04-09 21:48:24 +02004144 int kind;
4145
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004146 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004147 PyErr_BadArgument();
4148 return (Py_UCS4)-1;
4149 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004150 if (PyUnicode_READY(unicode) == -1) {
4151 return (Py_UCS4)-1;
4152 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004153 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004154 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004155 return (Py_UCS4)-1;
4156 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004157 data = PyUnicode_DATA(unicode);
4158 kind = PyUnicode_KIND(unicode);
4159 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004160}
4161
4162int
4163PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4164{
4165 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004166 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004167 return -1;
4168 }
Victor Stinner488fa492011-12-12 00:01:39 +01004169 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004170 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004171 PyErr_SetString(PyExc_IndexError, "string index out of range");
4172 return -1;
4173 }
Victor Stinner488fa492011-12-12 00:01:39 +01004174 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004175 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004176 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4177 PyErr_SetString(PyExc_ValueError, "character out of range");
4178 return -1;
4179 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004180 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4181 index, ch);
4182 return 0;
4183}
4184
Alexander Belopolsky40018472011-02-26 01:02:56 +00004185const char *
4186PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004187{
Victor Stinner42cb4622010-09-01 19:39:01 +00004188 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004189}
4190
Victor Stinner554f3f02010-06-16 23:33:54 +00004191/* create or adjust a UnicodeDecodeError */
4192static void
4193make_decode_exception(PyObject **exceptionObject,
4194 const char *encoding,
4195 const char *input, Py_ssize_t length,
4196 Py_ssize_t startpos, Py_ssize_t endpos,
4197 const char *reason)
4198{
4199 if (*exceptionObject == NULL) {
4200 *exceptionObject = PyUnicodeDecodeError_Create(
4201 encoding, input, length, startpos, endpos, reason);
4202 }
4203 else {
4204 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4205 goto onError;
4206 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4207 goto onError;
4208 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4209 goto onError;
4210 }
4211 return;
4212
4213onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004214 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004215}
4216
Steve Dowercc16be82016-09-08 10:35:16 -07004217#ifdef MS_WINDOWS
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004218static int
4219widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
4220{
4221 if (newsize > *size) {
4222 wchar_t *newbuf = *buf;
4223 if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
4224 PyErr_NoMemory();
4225 return -1;
4226 }
4227 *buf = newbuf;
4228 }
4229 *size = newsize;
4230 return 0;
4231}
4232
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004233/* error handling callback helper:
4234 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004235 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004236 and adjust various state variables.
4237 return 0 on success, -1 on error
4238*/
4239
Alexander Belopolsky40018472011-02-26 01:02:56 +00004240static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004241unicode_decode_call_errorhandler_wchar(
4242 const char *errors, PyObject **errorHandler,
4243 const char *encoding, const char *reason,
4244 const char **input, const char **inend, Py_ssize_t *startinpos,
4245 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004246 wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004247{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004248 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004249
4250 PyObject *restuple = NULL;
4251 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004252 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004253 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004254 Py_ssize_t requiredsize;
4255 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004256 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004257 wchar_t *repwstr;
4258 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004259
4260 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004261 *errorHandler = PyCodec_LookupError(errors);
4262 if (*errorHandler == NULL)
4263 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004264 }
4265
Victor Stinner554f3f02010-06-16 23:33:54 +00004266 make_decode_exception(exceptionObject,
4267 encoding,
4268 *input, *inend - *input,
4269 *startinpos, *endinpos,
4270 reason);
4271 if (*exceptionObject == NULL)
4272 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004273
Petr Viktorinffd97532020-02-11 17:46:57 +01004274 restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004275 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004276 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004277 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004278 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004279 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004280 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004281 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004282 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004283
4284 /* Copy back the bytes variables, which might have been modified by the
4285 callback */
4286 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4287 if (!inputobj)
4288 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004289 *input = PyBytes_AS_STRING(inputobj);
4290 insize = PyBytes_GET_SIZE(inputobj);
4291 *inend = *input + insize;
4292 /* we can DECREF safely, as the exception has another reference,
4293 so the object won't go away. */
4294 Py_DECREF(inputobj);
4295
4296 if (newpos<0)
4297 newpos = insize+newpos;
4298 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004299 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004300 goto onError;
4301 }
4302
4303 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4304 if (repwstr == NULL)
4305 goto onError;
4306 /* need more space? (at least enough for what we
4307 have+the replacement+the rest of the string (starting
4308 at the new input position), so we won't have to check space
4309 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004310 requiredsize = *outpos;
4311 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4312 goto overflow;
4313 requiredsize += repwlen;
4314 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4315 goto overflow;
4316 requiredsize += insize - newpos;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004317 outsize = *bufsize;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004318 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004319 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004320 requiredsize = 2*outsize;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004321 if (widechar_resize(buf, bufsize, requiredsize) < 0) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004322 goto onError;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004323 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004324 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004325 wcsncpy(*buf + *outpos, repwstr, repwlen);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004326 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004327 *endinpos = newpos;
4328 *inptr = *input + newpos;
4329
4330 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004331 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004332 return 0;
4333
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004334 overflow:
4335 PyErr_SetString(PyExc_OverflowError,
4336 "decoded result is too long for a Python string");
4337
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004338 onError:
4339 Py_XDECREF(restuple);
4340 return -1;
4341}
Steve Dowercc16be82016-09-08 10:35:16 -07004342#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004343
4344static int
4345unicode_decode_call_errorhandler_writer(
4346 const char *errors, PyObject **errorHandler,
4347 const char *encoding, const char *reason,
4348 const char **input, const char **inend, Py_ssize_t *startinpos,
4349 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4350 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4351{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004352 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004353
4354 PyObject *restuple = NULL;
4355 PyObject *repunicode = NULL;
4356 Py_ssize_t insize;
4357 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004358 Py_ssize_t replen;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004359 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004360 PyObject *inputobj = NULL;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004361 int need_to_grow = 0;
4362 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004363
4364 if (*errorHandler == NULL) {
4365 *errorHandler = PyCodec_LookupError(errors);
4366 if (*errorHandler == NULL)
4367 goto onError;
4368 }
4369
4370 make_decode_exception(exceptionObject,
4371 encoding,
4372 *input, *inend - *input,
4373 *startinpos, *endinpos,
4374 reason);
4375 if (*exceptionObject == NULL)
4376 goto onError;
4377
Petr Viktorinffd97532020-02-11 17:46:57 +01004378 restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004379 if (restuple == NULL)
4380 goto onError;
4381 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004382 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004383 goto onError;
4384 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004385 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004386 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004387
4388 /* Copy back the bytes variables, which might have been modified by the
4389 callback */
4390 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4391 if (!inputobj)
4392 goto onError;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004393 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004394 *input = PyBytes_AS_STRING(inputobj);
4395 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004396 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004397 /* we can DECREF safely, as the exception has another reference,
4398 so the object won't go away. */
4399 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004400
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004401 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004402 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004403 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004404 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004406 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004407
Victor Stinner170ca6f2013-04-18 00:25:28 +02004408 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004409 if (replen > 1) {
4410 writer->min_length += replen - 1;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004411 need_to_grow = 1;
4412 }
4413 new_inptr = *input + newpos;
4414 if (*inend - new_inptr > remain) {
4415 /* We don't know the decoding algorithm here so we make the worst
4416 assumption that one byte decodes to one unicode character.
4417 If unfortunately one byte could decode to more unicode characters,
4418 the decoder may write out-of-bound then. Is it possible for the
4419 algorithms using this function? */
4420 writer->min_length += *inend - new_inptr - remain;
4421 need_to_grow = 1;
4422 }
4423 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004424 writer->overallocate = 1;
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02004425 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004426 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4427 goto onError;
4428 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004429 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004430 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004431
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004432 *endinpos = newpos;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004433 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004434
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004435 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004436 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004437 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004438
Benjamin Peterson29060642009-01-31 22:14:21 +00004439 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004440 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004441 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004442}
4443
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004444/* --- UTF-7 Codec -------------------------------------------------------- */
4445
Antoine Pitrou244651a2009-05-04 18:56:13 +00004446/* See RFC2152 for details. We encode conservatively and decode liberally. */
4447
4448/* Three simple macros defining base-64. */
4449
4450/* Is c a base-64 character? */
4451
4452#define IS_BASE64(c) \
4453 (((c) >= 'A' && (c) <= 'Z') || \
4454 ((c) >= 'a' && (c) <= 'z') || \
4455 ((c) >= '0' && (c) <= '9') || \
4456 (c) == '+' || (c) == '/')
4457
4458/* given that c is a base-64 character, what is its base-64 value? */
4459
4460#define FROM_BASE64(c) \
4461 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4462 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4463 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4464 (c) == '+' ? 62 : 63)
4465
4466/* What is the base-64 character of the bottom 6 bits of n? */
4467
4468#define TO_BASE64(n) \
4469 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4470
4471/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4472 * decoded as itself. We are permissive on decoding; the only ASCII
4473 * byte not decoding to itself is the + which begins a base64
4474 * string. */
4475
4476#define DECODE_DIRECT(c) \
4477 ((c) <= 127 && (c) != '+')
4478
4479/* The UTF-7 encoder treats ASCII characters differently according to
4480 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4481 * the above). See RFC2152. This array identifies these different
4482 * sets:
4483 * 0 : "Set D"
4484 * alphanumeric and '(),-./:?
4485 * 1 : "Set O"
4486 * !"#$%&*;<=>@[]^_`{|}
4487 * 2 : "whitespace"
4488 * ht nl cr sp
4489 * 3 : special (must be base64 encoded)
4490 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4491 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004492
Tim Petersced69f82003-09-16 20:30:58 +00004493static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004494char utf7_category[128] = {
4495/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4496 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4497/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4498 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4499/* sp ! " # $ % & ' ( ) * + , - . / */
4500 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4501/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4502 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4503/* @ A B C D E F G H I J K L M N O */
4504 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4505/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4506 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4507/* ` a b c d e f g h i j k l m n o */
4508 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4509/* p q r s t u v w x y z { | } ~ del */
4510 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004511};
4512
Antoine Pitrou244651a2009-05-04 18:56:13 +00004513/* ENCODE_DIRECT: this character should be encoded as itself. The
4514 * answer depends on whether we are encoding set O as itself, and also
4515 * on whether we are encoding whitespace as itself. RFC2152 makes it
4516 * clear that the answers to these questions vary between
4517 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004518
Antoine Pitrou244651a2009-05-04 18:56:13 +00004519#define ENCODE_DIRECT(c, directO, directWS) \
4520 ((c) < 128 && (c) > 0 && \
4521 ((utf7_category[(c)] == 0) || \
4522 (directWS && (utf7_category[(c)] == 2)) || \
4523 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524
Alexander Belopolsky40018472011-02-26 01:02:56 +00004525PyObject *
4526PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004527 Py_ssize_t size,
4528 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004529{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004530 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4531}
4532
Antoine Pitrou244651a2009-05-04 18:56:13 +00004533/* The decoder. The only state we preserve is our read position,
4534 * i.e. how many characters we have consumed. So if we end in the
4535 * middle of a shift sequence we have to back off the read position
4536 * and the output to the beginning of the sequence, otherwise we lose
4537 * all the shift state (seen bits, number of bits seen, high
4538 * surrogate). */
4539
Alexander Belopolsky40018472011-02-26 01:02:56 +00004540PyObject *
4541PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004542 Py_ssize_t size,
4543 const char *errors,
4544 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004545{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004546 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004547 Py_ssize_t startinpos;
4548 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004549 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004550 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004551 const char *errmsg = "";
4552 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004553 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004554 unsigned int base64bits = 0;
4555 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004556 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004557 PyObject *errorHandler = NULL;
4558 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004559
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004560 if (size == 0) {
4561 if (consumed)
4562 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004563 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004564 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004565
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004566 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004567 _PyUnicodeWriter_Init(&writer);
4568 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004569
4570 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004571 e = s + size;
4572
4573 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004574 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004575 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004576 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004577
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 if (inShift) { /* in a base-64 section */
4579 if (IS_BASE64(ch)) { /* consume a base-64 character */
4580 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4581 base64bits += 6;
4582 s++;
4583 if (base64bits >= 16) {
4584 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004585 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004586 base64bits -= 16;
4587 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004588 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004589 if (surrogate) {
4590 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004591 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4592 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004593 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004594 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004595 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004596 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004597 }
4598 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004599 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004600 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004601 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004602 }
4603 }
Victor Stinner551ac952011-11-29 22:58:13 +01004604 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004605 /* first surrogate */
4606 surrogate = outCh;
4607 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004608 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004609 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004610 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004611 }
4612 }
4613 }
4614 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004615 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004616 if (base64bits > 0) { /* left-over bits */
4617 if (base64bits >= 6) {
4618 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004619 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004620 errmsg = "partial character in shift sequence";
4621 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004622 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004623 else {
4624 /* Some bits remain; they should be zero */
4625 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004626 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004627 errmsg = "non-zero padding bits in shift sequence";
4628 goto utf7Error;
4629 }
4630 }
4631 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004632 if (surrogate && DECODE_DIRECT(ch)) {
4633 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4634 goto onError;
4635 }
4636 surrogate = 0;
4637 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004638 /* '-' is absorbed; other terminating
4639 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004640 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004641 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004642 }
4643 }
4644 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004645 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004646 s++; /* consume '+' */
4647 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004648 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004649 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004650 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004651 }
Zackery Spytze349bf22018-08-18 22:43:38 -06004652 else if (s < e && !IS_BASE64(*s)) {
4653 s++;
4654 errmsg = "ill-formed sequence";
4655 goto utf7Error;
4656 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004657 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004658 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004659 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004660 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004662 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004663 }
4664 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004665 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004666 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004667 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004668 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004669 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004670 else {
4671 startinpos = s-starts;
4672 s++;
4673 errmsg = "unexpected special character";
4674 goto utf7Error;
4675 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004676 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004677utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004678 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004679 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004680 errors, &errorHandler,
4681 "utf7", errmsg,
4682 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004683 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004684 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004685 }
4686
Antoine Pitrou244651a2009-05-04 18:56:13 +00004687 /* end of string */
4688
4689 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4690 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004691 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004692 if (surrogate ||
4693 (base64bits >= 6) ||
4694 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004695 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004696 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004697 errors, &errorHandler,
4698 "utf7", "unterminated shift sequence",
4699 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004700 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004701 goto onError;
4702 if (s < e)
4703 goto restart;
4704 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004705 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004706
4707 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004708 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004709 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004710 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004711 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004712 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004713 writer.kind, writer.data, shiftOutStart);
4714 Py_XDECREF(errorHandler);
4715 Py_XDECREF(exc);
4716 _PyUnicodeWriter_Dealloc(&writer);
4717 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004718 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004719 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004720 }
4721 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004722 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004723 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004724 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004725
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004726 Py_XDECREF(errorHandler);
4727 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004728 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004729
Benjamin Peterson29060642009-01-31 22:14:21 +00004730 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004731 Py_XDECREF(errorHandler);
4732 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004733 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004734 return NULL;
4735}
4736
4737
Alexander Belopolsky40018472011-02-26 01:02:56 +00004738PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004739_PyUnicode_EncodeUTF7(PyObject *str,
4740 int base64SetO,
4741 int base64WhiteSpace,
4742 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004743{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004744 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03004745 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004746 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004747 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004748 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004749 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004750 unsigned int base64bits = 0;
4751 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004752 char * out;
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004753 const char * start;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004754
Benjamin Petersonbac79492012-01-14 13:34:47 -05004755 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004756 return NULL;
4757 kind = PyUnicode_KIND(str);
4758 data = PyUnicode_DATA(str);
4759 len = PyUnicode_GET_LENGTH(str);
4760
4761 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004762 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004763
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004764 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004765 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004766 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004767 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004768 if (v == NULL)
4769 return NULL;
4770
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004771 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004772 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004773 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004774
Antoine Pitrou244651a2009-05-04 18:56:13 +00004775 if (inShift) {
4776 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4777 /* shifting out */
4778 if (base64bits) { /* output remaining bits */
4779 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4780 base64buffer = 0;
4781 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004782 }
4783 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004784 /* Characters not in the BASE64 set implicitly unshift the sequence
4785 so no '-' is required, except if the character is itself a '-' */
4786 if (IS_BASE64(ch) || ch == '-') {
4787 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004788 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004789 *out++ = (char) ch;
4790 }
4791 else {
4792 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004793 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004794 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004795 else { /* not in a shift sequence */
4796 if (ch == '+') {
4797 *out++ = '+';
4798 *out++ = '-';
4799 }
4800 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4801 *out++ = (char) ch;
4802 }
4803 else {
4804 *out++ = '+';
4805 inShift = 1;
4806 goto encode_char;
4807 }
4808 }
4809 continue;
4810encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004811 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004812 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004813
Antoine Pitrou244651a2009-05-04 18:56:13 +00004814 /* code first surrogate */
4815 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004816 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004817 while (base64bits >= 6) {
4818 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4819 base64bits -= 6;
4820 }
4821 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004822 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004823 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004824 base64bits += 16;
4825 base64buffer = (base64buffer << 16) | ch;
4826 while (base64bits >= 6) {
4827 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4828 base64bits -= 6;
4829 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004830 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004831 if (base64bits)
4832 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4833 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004834 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004835 if (_PyBytes_Resize(&v, out - start) < 0)
4836 return NULL;
4837 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004838}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004839PyObject *
4840PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4841 Py_ssize_t size,
4842 int base64SetO,
4843 int base64WhiteSpace,
4844 const char *errors)
4845{
4846 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004847 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004848 if (tmp == NULL)
4849 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004850 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004851 base64WhiteSpace, errors);
4852 Py_DECREF(tmp);
4853 return result;
4854}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004855
Antoine Pitrou244651a2009-05-04 18:56:13 +00004856#undef IS_BASE64
4857#undef FROM_BASE64
4858#undef TO_BASE64
4859#undef DECODE_DIRECT
4860#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004861
Guido van Rossumd57fd912000-03-10 22:53:23 +00004862/* --- UTF-8 Codec -------------------------------------------------------- */
4863
Alexander Belopolsky40018472011-02-26 01:02:56 +00004864PyObject *
4865PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004866 Py_ssize_t size,
4867 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004868{
Walter Dörwald69652032004-09-07 20:24:22 +00004869 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4870}
4871
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004872#include "stringlib/asciilib.h"
4873#include "stringlib/codecs.h"
4874#include "stringlib/undef.h"
4875
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004876#include "stringlib/ucs1lib.h"
4877#include "stringlib/codecs.h"
4878#include "stringlib/undef.h"
4879
4880#include "stringlib/ucs2lib.h"
4881#include "stringlib/codecs.h"
4882#include "stringlib/undef.h"
4883
4884#include "stringlib/ucs4lib.h"
4885#include "stringlib/codecs.h"
4886#include "stringlib/undef.h"
4887
Antoine Pitrouab868312009-01-10 15:40:25 +00004888/* Mask to quickly check whether a C 'long' contains a
4889 non-ASCII, UTF8-encoded char. */
4890#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004891# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004892#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004893# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004894#else
4895# error C 'long' size should be either 4 or 8!
4896#endif
4897
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004898static Py_ssize_t
4899ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004900{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004901 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004902 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004903
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004904 /*
4905 * Issue #17237: m68k is a bit different from most architectures in
4906 * that objects do not use "natural alignment" - for example, int and
4907 * long are only aligned at 2-byte boundaries. Therefore the assert()
4908 * won't work; also, tests have shown that skipping the "optimised
4909 * version" will even speed up m68k.
4910 */
4911#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004912#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004913 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4914 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004915 /* Fast path, see in STRINGLIB(utf8_decode) for
4916 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004917 /* Help allocation */
4918 const char *_p = p;
4919 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004920 while (_p < aligned_end) {
4921 unsigned long value = *(const unsigned long *) _p;
4922 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004923 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004924 *((unsigned long *)q) = value;
4925 _p += SIZEOF_LONG;
4926 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004927 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004928 p = _p;
4929 while (p < end) {
4930 if ((unsigned char)*p & 0x80)
4931 break;
4932 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004933 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004934 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004935 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004936#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004937#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004938 while (p < end) {
4939 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4940 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004941 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004942 /* Help allocation */
4943 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004944 while (_p < aligned_end) {
Andy Lestere6be9b52020-02-11 20:28:35 -06004945 unsigned long value = *(const unsigned long *) _p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004946 if (value & ASCII_CHAR_MASK)
4947 break;
4948 _p += SIZEOF_LONG;
4949 }
4950 p = _p;
4951 if (_p == end)
4952 break;
4953 }
4954 if ((unsigned char)*p & 0x80)
4955 break;
4956 ++p;
4957 }
4958 memcpy(dest, start, p - start);
4959 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004960}
Antoine Pitrouab868312009-01-10 15:40:25 +00004961
Victor Stinner709d23d2019-05-02 14:56:30 -04004962static PyObject *
4963unicode_decode_utf8(const char *s, Py_ssize_t size,
4964 _Py_error_handler error_handler, const char *errors,
4965 Py_ssize_t *consumed)
Victor Stinner785938e2011-12-11 20:09:03 +01004966{
Victor Stinner785938e2011-12-11 20:09:03 +01004967 if (size == 0) {
4968 if (consumed)
4969 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004970 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004971 }
4972
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004973 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4974 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004975 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004976 *consumed = 1;
4977 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004978 }
4979
Inada Naoki770847a2019-06-24 12:30:24 +09004980 const char *starts = s;
4981 const char *end = s + size;
Victor Stinner785938e2011-12-11 20:09:03 +01004982
Inada Naoki770847a2019-06-24 12:30:24 +09004983 // fast path: try ASCII string.
4984 PyObject *u = PyUnicode_New(size, 127);
4985 if (u == NULL) {
4986 return NULL;
4987 }
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03004988 s += ascii_decode(s, end, PyUnicode_1BYTE_DATA(u));
Inada Naoki770847a2019-06-24 12:30:24 +09004989 if (s == end) {
4990 return u;
4991 }
4992
4993 // Use _PyUnicodeWriter after fast path is failed.
4994 _PyUnicodeWriter writer;
4995 _PyUnicodeWriter_InitWithBuffer(&writer, u);
4996 writer.pos = s - starts;
4997
4998 Py_ssize_t startinpos, endinpos;
4999 const char *errmsg = "";
5000 PyObject *error_handler_obj = NULL;
5001 PyObject *exc = NULL;
5002
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005003 while (s < end) {
5004 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005005 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02005006
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005007 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005008 if (PyUnicode_IS_ASCII(writer.buffer))
5009 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005010 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005011 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005012 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005013 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005014 } else {
5015 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005016 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005017 }
5018
5019 switch (ch) {
5020 case 0:
5021 if (s == end || consumed)
5022 goto End;
5023 errmsg = "unexpected end of data";
5024 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005025 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005026 break;
5027 case 1:
5028 errmsg = "invalid start byte";
5029 startinpos = s - starts;
5030 endinpos = startinpos + 1;
5031 break;
5032 case 2:
Serhiy Storchaka894263b2019-06-25 11:54:18 +03005033 if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
5034 && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
5035 {
5036 /* Truncated surrogate code in range D800-DFFF */
Serhiy Storchaka7a465cb2019-03-30 08:23:38 +02005037 goto End;
5038 }
Serhiy Storchaka894263b2019-06-25 11:54:18 +03005039 /* fall through */
5040 case 3:
5041 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005042 errmsg = "invalid continuation byte";
5043 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02005044 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005045 break;
5046 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005047 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005048 goto onError;
5049 continue;
5050 }
5051
Victor Stinner1d65d912015-10-05 13:43:50 +02005052 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02005053 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner1d65d912015-10-05 13:43:50 +02005054
5055 switch (error_handler) {
5056 case _Py_ERROR_IGNORE:
5057 s += (endinpos - startinpos);
5058 break;
5059
5060 case _Py_ERROR_REPLACE:
5061 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
5062 goto onError;
5063 s += (endinpos - startinpos);
5064 break;
5065
5066 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02005067 {
5068 Py_ssize_t i;
5069
Victor Stinner1d65d912015-10-05 13:43:50 +02005070 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
5071 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005072 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02005073 ch = (Py_UCS4)(unsigned char)(starts[i]);
5074 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
5075 ch + 0xdc00);
5076 writer.pos++;
5077 }
5078 s += (endinpos - startinpos);
5079 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02005080 }
Victor Stinner1d65d912015-10-05 13:43:50 +02005081
5082 default:
5083 if (unicode_decode_call_errorhandler_writer(
5084 errors, &error_handler_obj,
5085 "utf-8", errmsg,
5086 &starts, &end, &startinpos, &endinpos, &exc, &s,
5087 &writer))
5088 goto onError;
5089 }
Victor Stinner785938e2011-12-11 20:09:03 +01005090 }
5091
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005092End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005093 if (consumed)
5094 *consumed = s - starts;
5095
Victor Stinner1d65d912015-10-05 13:43:50 +02005096 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005097 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005098 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005099
5100onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02005101 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005102 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005103 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005104 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01005105}
5106
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005107
Victor Stinner709d23d2019-05-02 14:56:30 -04005108PyObject *
5109PyUnicode_DecodeUTF8Stateful(const char *s,
5110 Py_ssize_t size,
5111 const char *errors,
5112 Py_ssize_t *consumed)
5113{
5114 return unicode_decode_utf8(s, size, _Py_ERROR_UNKNOWN, errors, consumed);
5115}
5116
5117
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005118/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
5119 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01005120
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005121 On success, write a pointer to a newly allocated wide character string into
5122 *wstr (use PyMem_RawFree() to free the memory) and write the output length
5123 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005124
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005125 On memory allocation failure, return -1.
5126
5127 On decoding error (if surrogateescape is zero), return -2. If wlen is
5128 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
5129 is not NULL, write the decoding error message into *reason. */
5130int
5131_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005132 const char **reason, _Py_error_handler errors)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005133{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005134 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005135 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005136 wchar_t *unicode;
5137 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005138
Victor Stinner3d4226a2018-08-29 22:21:32 +02005139 int surrogateescape = 0;
5140 int surrogatepass = 0;
5141 switch (errors)
5142 {
5143 case _Py_ERROR_STRICT:
5144 break;
5145 case _Py_ERROR_SURROGATEESCAPE:
5146 surrogateescape = 1;
5147 break;
5148 case _Py_ERROR_SURROGATEPASS:
5149 surrogatepass = 1;
5150 break;
5151 default:
5152 return -3;
5153 }
5154
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005155 /* Note: size will always be longer than the resulting Unicode
5156 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01005157 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005158 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01005159 }
5160
Victor Stinner6f8eeee2013-07-07 22:57:45 +02005161 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01005162 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005163 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01005164 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005165
5166 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005167 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005168 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005169 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005170 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005171#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005172 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005173#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005174 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005175#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005176 if (ch > 0xFF) {
5177#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005178 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005179#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005180 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005181 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005182 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5183 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5184#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005185 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005186 else {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005187 if (!ch && s == e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005188 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005189 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005190
5191 if (surrogateescape) {
5192 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5193 }
5194 else {
5195 /* Is it a valid three-byte code? */
5196 if (surrogatepass
5197 && (e - s) >= 3
5198 && (s[0] & 0xf0) == 0xe0
5199 && (s[1] & 0xc0) == 0x80
5200 && (s[2] & 0xc0) == 0x80)
5201 {
5202 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5203 s += 3;
5204 unicode[outpos++] = ch;
5205 }
5206 else {
5207 PyMem_RawFree(unicode );
5208 if (reason != NULL) {
5209 switch (ch) {
5210 case 0:
5211 *reason = "unexpected end of data";
5212 break;
5213 case 1:
5214 *reason = "invalid start byte";
5215 break;
5216 /* 2, 3, 4 */
5217 default:
5218 *reason = "invalid continuation byte";
5219 break;
5220 }
5221 }
5222 if (wlen != NULL) {
5223 *wlen = s - orig_s;
5224 }
5225 return -2;
5226 }
5227 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005228 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005229 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005230 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005231 if (wlen) {
5232 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005233 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005234 *wstr = unicode;
5235 return 0;
5236}
5237
Victor Stinner5f9cf232019-03-19 01:46:25 +01005238
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005239wchar_t*
Victor Stinner5f9cf232019-03-19 01:46:25 +01005240_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
5241 size_t *wlen)
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005242{
5243 wchar_t *wstr;
Victor Stinner5f9cf232019-03-19 01:46:25 +01005244 int res = _Py_DecodeUTF8Ex(arg, arglen,
5245 &wstr, wlen,
5246 NULL, _Py_ERROR_SURROGATEESCAPE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005247 if (res != 0) {
Victor Stinner5f9cf232019-03-19 01:46:25 +01005248 /* _Py_DecodeUTF8Ex() must support _Py_ERROR_SURROGATEESCAPE */
5249 assert(res != -3);
5250 if (wlen) {
5251 *wlen = (size_t)res;
5252 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005253 return NULL;
5254 }
5255 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005256}
5257
Antoine Pitrouab868312009-01-10 15:40:25 +00005258
Victor Stinnere47e6982017-12-21 15:45:16 +01005259/* UTF-8 encoder using the surrogateescape error handler .
5260
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005261 On success, return 0 and write the newly allocated character string (use
5262 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005263
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005264 On encoding failure, return -2 and write the position of the invalid
5265 surrogate character into *error_pos (if error_pos is set) and the decoding
5266 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005267
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005268 On memory allocation failure, return -1. */
5269int
5270_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005271 const char **reason, int raw_malloc, _Py_error_handler errors)
Victor Stinnere47e6982017-12-21 15:45:16 +01005272{
5273 const Py_ssize_t max_char_size = 4;
5274 Py_ssize_t len = wcslen(text);
5275
5276 assert(len >= 0);
5277
Victor Stinner3d4226a2018-08-29 22:21:32 +02005278 int surrogateescape = 0;
5279 int surrogatepass = 0;
5280 switch (errors)
5281 {
5282 case _Py_ERROR_STRICT:
5283 break;
5284 case _Py_ERROR_SURROGATEESCAPE:
5285 surrogateescape = 1;
5286 break;
5287 case _Py_ERROR_SURROGATEPASS:
5288 surrogatepass = 1;
5289 break;
5290 default:
5291 return -3;
5292 }
5293
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005294 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5295 return -1;
5296 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005297 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005298 if (raw_malloc) {
5299 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005300 }
5301 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005302 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005303 }
5304 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005305 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005306 }
5307
5308 char *p = bytes;
5309 Py_ssize_t i;
Victor Stinner3d4226a2018-08-29 22:21:32 +02005310 for (i = 0; i < len; ) {
5311 Py_ssize_t ch_pos = i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005312 Py_UCS4 ch = text[i];
Victor Stinner3d4226a2018-08-29 22:21:32 +02005313 i++;
5314#if Py_UNICODE_SIZE == 2
5315 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
5316 && i < len
5317 && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5318 {
5319 ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5320 i++;
5321 }
5322#endif
Victor Stinnere47e6982017-12-21 15:45:16 +01005323
5324 if (ch < 0x80) {
5325 /* Encode ASCII */
5326 *p++ = (char) ch;
5327
5328 }
5329 else if (ch < 0x0800) {
5330 /* Encode Latin-1 */
5331 *p++ = (char)(0xc0 | (ch >> 6));
5332 *p++ = (char)(0x80 | (ch & 0x3f));
5333 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005334 else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005335 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005336 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005337 if (error_pos != NULL) {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005338 *error_pos = (size_t)ch_pos;
Victor Stinnere47e6982017-12-21 15:45:16 +01005339 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005340 if (reason != NULL) {
5341 *reason = "encoding error";
5342 }
5343 if (raw_malloc) {
5344 PyMem_RawFree(bytes);
5345 }
5346 else {
5347 PyMem_Free(bytes);
5348 }
5349 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005350 }
5351 *p++ = (char)(ch & 0xff);
5352 }
5353 else if (ch < 0x10000) {
5354 *p++ = (char)(0xe0 | (ch >> 12));
5355 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5356 *p++ = (char)(0x80 | (ch & 0x3f));
5357 }
5358 else { /* ch >= 0x10000 */
5359 assert(ch <= MAX_UNICODE);
5360 /* Encode UCS4 Unicode ordinals */
5361 *p++ = (char)(0xf0 | (ch >> 18));
5362 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5363 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5364 *p++ = (char)(0x80 | (ch & 0x3f));
5365 }
5366 }
5367 *p++ = '\0';
5368
5369 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005370 char *bytes2;
5371 if (raw_malloc) {
5372 bytes2 = PyMem_RawRealloc(bytes, final_size);
5373 }
5374 else {
5375 bytes2 = PyMem_Realloc(bytes, final_size);
5376 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005377 if (bytes2 == NULL) {
5378 if (error_pos != NULL) {
5379 *error_pos = (size_t)-1;
5380 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005381 if (raw_malloc) {
5382 PyMem_RawFree(bytes);
5383 }
5384 else {
5385 PyMem_Free(bytes);
5386 }
5387 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005388 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005389 *str = bytes2;
5390 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005391}
5392
5393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005394/* Primary internal function which creates utf8 encoded bytes objects.
5395
5396 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005397 and allocate exactly as much space needed at the end. Else allocate the
5398 maximum possible needed (4 result bytes per Unicode character), and return
5399 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005400*/
Victor Stinner709d23d2019-05-02 14:56:30 -04005401static PyObject *
5402unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
5403 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005404{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005405 if (!PyUnicode_Check(unicode)) {
5406 PyErr_BadArgument();
5407 return NULL;
5408 }
5409
5410 if (PyUnicode_READY(unicode) == -1)
5411 return NULL;
5412
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005413 if (PyUnicode_UTF8(unicode))
5414 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5415 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005416
Inada Naoki02a4d572020-02-27 13:48:59 +09005417 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03005418 const void *data = PyUnicode_DATA(unicode);
Inada Naoki02a4d572020-02-27 13:48:59 +09005419 Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5420
5421 _PyBytesWriter writer;
5422 char *end;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005423
Benjamin Petersonead6b532011-12-20 17:23:42 -06005424 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005425 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005426 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005427 case PyUnicode_1BYTE_KIND:
5428 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5429 assert(!PyUnicode_IS_ASCII(unicode));
Inada Naoki02a4d572020-02-27 13:48:59 +09005430 end = ucs1lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
5431 break;
Victor Stinner6099a032011-12-18 14:22:26 +01005432 case PyUnicode_2BYTE_KIND:
Inada Naoki02a4d572020-02-27 13:48:59 +09005433 end = ucs2lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
5434 break;
Victor Stinner6099a032011-12-18 14:22:26 +01005435 case PyUnicode_4BYTE_KIND:
Inada Naoki02a4d572020-02-27 13:48:59 +09005436 end = ucs4lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
5437 break;
Tim Peters602f7402002-04-27 18:03:26 +00005438 }
Inada Naoki02a4d572020-02-27 13:48:59 +09005439
5440 if (end == NULL) {
5441 _PyBytesWriter_Dealloc(&writer);
5442 return NULL;
5443 }
5444 return _PyBytesWriter_Finish(&writer, end);
5445}
5446
5447static int
5448unicode_fill_utf8(PyObject *unicode)
5449{
5450 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5451 assert(!PyUnicode_IS_ASCII(unicode));
5452
5453 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03005454 const void *data = PyUnicode_DATA(unicode);
Inada Naoki02a4d572020-02-27 13:48:59 +09005455 Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
5456
5457 _PyBytesWriter writer;
5458 char *end;
5459
5460 switch (kind) {
5461 default:
5462 Py_UNREACHABLE();
5463 case PyUnicode_1BYTE_KIND:
5464 end = ucs1lib_utf8_encoder(&writer, unicode, data, size,
5465 _Py_ERROR_STRICT, NULL);
5466 break;
5467 case PyUnicode_2BYTE_KIND:
5468 end = ucs2lib_utf8_encoder(&writer, unicode, data, size,
5469 _Py_ERROR_STRICT, NULL);
5470 break;
5471 case PyUnicode_4BYTE_KIND:
5472 end = ucs4lib_utf8_encoder(&writer, unicode, data, size,
5473 _Py_ERROR_STRICT, NULL);
5474 break;
5475 }
5476 if (end == NULL) {
5477 _PyBytesWriter_Dealloc(&writer);
5478 return -1;
5479 }
5480
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03005481 const char *start = writer.use_small_buffer ? writer.small_buffer :
Inada Naoki02a4d572020-02-27 13:48:59 +09005482 PyBytes_AS_STRING(writer.buffer);
5483 Py_ssize_t len = end - start;
5484
5485 char *cache = PyObject_MALLOC(len + 1);
5486 if (cache == NULL) {
5487 _PyBytesWriter_Dealloc(&writer);
5488 PyErr_NoMemory();
5489 return -1;
5490 }
5491 _PyUnicode_UTF8(unicode) = cache;
5492 _PyUnicode_UTF8_LENGTH(unicode) = len;
5493 memcpy(cache, start, len);
5494 cache[len] = '\0';
5495 _PyBytesWriter_Dealloc(&writer);
5496 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497}
5498
Alexander Belopolsky40018472011-02-26 01:02:56 +00005499PyObject *
Victor Stinner709d23d2019-05-02 14:56:30 -04005500_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
5501{
5502 return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
5503}
5504
5505
5506PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005507PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5508 Py_ssize_t size,
5509 const char *errors)
5510{
5511 PyObject *v, *unicode;
5512
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005513 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005514 if (unicode == NULL)
5515 return NULL;
5516 v = _PyUnicode_AsUTF8String(unicode, errors);
5517 Py_DECREF(unicode);
5518 return v;
5519}
5520
5521PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005522PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005523{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005524 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005525}
5526
Walter Dörwald41980ca2007-08-16 21:55:45 +00005527/* --- UTF-32 Codec ------------------------------------------------------- */
5528
5529PyObject *
5530PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005531 Py_ssize_t size,
5532 const char *errors,
5533 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005534{
5535 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5536}
5537
5538PyObject *
5539PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005540 Py_ssize_t size,
5541 const char *errors,
5542 int *byteorder,
5543 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005544{
5545 const char *starts = s;
5546 Py_ssize_t startinpos;
5547 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005548 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005549 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005550 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005551 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005552 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005553 PyObject *errorHandler = NULL;
5554 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005555
Andy Lestere6be9b52020-02-11 20:28:35 -06005556 q = (const unsigned char *)s;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005557 e = q + size;
5558
5559 if (byteorder)
5560 bo = *byteorder;
5561
5562 /* Check for BOM marks (U+FEFF) in the input and adjust current
5563 byte order setting accordingly. In native mode, the leading BOM
5564 mark is skipped, in all other modes, it is copied to the output
5565 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005566 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005567 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005568 if (bom == 0x0000FEFF) {
5569 bo = -1;
5570 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005571 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005572 else if (bom == 0xFFFE0000) {
5573 bo = 1;
5574 q += 4;
5575 }
5576 if (byteorder)
5577 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005578 }
5579
Victor Stinnere64322e2012-10-30 23:12:47 +01005580 if (q == e) {
5581 if (consumed)
5582 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005583 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005584 }
5585
Victor Stinnere64322e2012-10-30 23:12:47 +01005586#ifdef WORDS_BIGENDIAN
5587 le = bo < 0;
5588#else
5589 le = bo <= 0;
5590#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005591 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005592
Victor Stinner8f674cc2013-04-17 23:02:17 +02005593 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005594 writer.min_length = (e - q + 3) / 4;
5595 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005596 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005597
Victor Stinnere64322e2012-10-30 23:12:47 +01005598 while (1) {
5599 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005600 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005601
Victor Stinnere64322e2012-10-30 23:12:47 +01005602 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005603 enum PyUnicode_Kind kind = writer.kind;
5604 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005605 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005606 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005607 if (le) {
5608 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005609 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005610 if (ch > maxch)
5611 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005612 if (kind != PyUnicode_1BYTE_KIND &&
5613 Py_UNICODE_IS_SURROGATE(ch))
5614 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005615 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005616 q += 4;
5617 } while (q <= last);
5618 }
5619 else {
5620 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005621 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005622 if (ch > maxch)
5623 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005624 if (kind != PyUnicode_1BYTE_KIND &&
5625 Py_UNICODE_IS_SURROGATE(ch))
5626 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005627 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005628 q += 4;
5629 } while (q <= last);
5630 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005631 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005632 }
5633
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005634 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005635 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005636 startinpos = ((const char *)q) - starts;
5637 endinpos = startinpos + 4;
5638 }
5639 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005640 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005641 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005642 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005643 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005644 startinpos = ((const char *)q) - starts;
5645 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005646 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005647 else {
5648 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005649 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005650 goto onError;
5651 q += 4;
5652 continue;
5653 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005654 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005655 startinpos = ((const char *)q) - starts;
5656 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005657 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005658
5659 /* The remaining input chars are ignored if the callback
5660 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005661 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005662 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005663 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005664 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005665 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005666 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005667 }
5668
Walter Dörwald41980ca2007-08-16 21:55:45 +00005669 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005670 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005671
Walter Dörwald41980ca2007-08-16 21:55:45 +00005672 Py_XDECREF(errorHandler);
5673 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005674 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005675
Benjamin Peterson29060642009-01-31 22:14:21 +00005676 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005677 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005678 Py_XDECREF(errorHandler);
5679 Py_XDECREF(exc);
5680 return NULL;
5681}
5682
5683PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005684_PyUnicode_EncodeUTF32(PyObject *str,
5685 const char *errors,
5686 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005687{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005688 enum PyUnicode_Kind kind;
5689 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005690 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005691 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005692 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005693#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005694 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005695#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005696 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005697#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005698 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005699 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005700 PyObject *errorHandler = NULL;
5701 PyObject *exc = NULL;
5702 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005703
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005704 if (!PyUnicode_Check(str)) {
5705 PyErr_BadArgument();
5706 return NULL;
5707 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005708 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005709 return NULL;
5710 kind = PyUnicode_KIND(str);
5711 data = PyUnicode_DATA(str);
5712 len = PyUnicode_GET_LENGTH(str);
5713
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005714 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005715 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005716 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005717 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005718 if (v == NULL)
5719 return NULL;
5720
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005721 /* output buffer is 4-bytes aligned */
5722 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005723 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005724 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005725 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005726 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005727 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005728
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005729 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005730 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005731 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005732 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005733 else
5734 encoding = "utf-32";
5735
5736 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005737 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5738 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005739 }
5740
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005741 pos = 0;
5742 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005743 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005744
5745 if (kind == PyUnicode_2BYTE_KIND) {
5746 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5747 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005748 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005749 else {
5750 assert(kind == PyUnicode_4BYTE_KIND);
5751 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5752 &out, native_ordering);
5753 }
5754 if (pos == len)
5755 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005756
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005757 rep = unicode_encode_call_errorhandler(
5758 errors, &errorHandler,
5759 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005760 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005761 if (!rep)
5762 goto error;
5763
5764 if (PyBytes_Check(rep)) {
5765 repsize = PyBytes_GET_SIZE(rep);
5766 if (repsize & 3) {
5767 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005768 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005769 "surrogates not allowed");
5770 goto error;
5771 }
5772 moreunits = repsize / 4;
5773 }
5774 else {
5775 assert(PyUnicode_Check(rep));
5776 if (PyUnicode_READY(rep) < 0)
5777 goto error;
5778 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5779 if (!PyUnicode_IS_ASCII(rep)) {
5780 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005781 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005782 "surrogates not allowed");
5783 goto error;
5784 }
5785 }
5786
5787 /* four bytes are reserved for each surrogate */
5788 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005789 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005790 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005791 /* integer overflow */
5792 PyErr_NoMemory();
5793 goto error;
5794 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005795 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005796 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005797 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005798 }
5799
5800 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005801 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005802 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005803 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005804 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005805 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5806 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005807 }
5808
5809 Py_CLEAR(rep);
5810 }
5811
5812 /* Cut back to size actually needed. This is necessary for, for example,
5813 encoding of a string containing isolated surrogates and the 'ignore'
5814 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005815 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005816 if (nsize != PyBytes_GET_SIZE(v))
5817 _PyBytes_Resize(&v, nsize);
5818 Py_XDECREF(errorHandler);
5819 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005820 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005821 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005822 error:
5823 Py_XDECREF(rep);
5824 Py_XDECREF(errorHandler);
5825 Py_XDECREF(exc);
5826 Py_XDECREF(v);
5827 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005828}
5829
Alexander Belopolsky40018472011-02-26 01:02:56 +00005830PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005831PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5832 Py_ssize_t size,
5833 const char *errors,
5834 int byteorder)
5835{
5836 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005837 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005838 if (tmp == NULL)
5839 return NULL;
5840 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5841 Py_DECREF(tmp);
5842 return result;
5843}
5844
5845PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005846PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005847{
Victor Stinnerb960b342011-11-20 19:12:52 +01005848 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005849}
5850
Guido van Rossumd57fd912000-03-10 22:53:23 +00005851/* --- UTF-16 Codec ------------------------------------------------------- */
5852
Tim Peters772747b2001-08-09 22:21:55 +00005853PyObject *
5854PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005855 Py_ssize_t size,
5856 const char *errors,
5857 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005858{
Walter Dörwald69652032004-09-07 20:24:22 +00005859 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5860}
5861
5862PyObject *
5863PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005864 Py_ssize_t size,
5865 const char *errors,
5866 int *byteorder,
5867 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005868{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005870 Py_ssize_t startinpos;
5871 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005872 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005873 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005874 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005875 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005876 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005877 PyObject *errorHandler = NULL;
5878 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005879 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880
Andy Lestere6be9b52020-02-11 20:28:35 -06005881 q = (const unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005882 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005883
5884 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005885 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005887 /* Check for BOM marks (U+FEFF) in the input and adjust current
5888 byte order setting accordingly. In native mode, the leading BOM
5889 mark is skipped, in all other modes, it is copied to the output
5890 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005891 if (bo == 0 && size >= 2) {
5892 const Py_UCS4 bom = (q[1] << 8) | q[0];
5893 if (bom == 0xFEFF) {
5894 q += 2;
5895 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005897 else if (bom == 0xFFFE) {
5898 q += 2;
5899 bo = 1;
5900 }
5901 if (byteorder)
5902 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005903 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005904
Antoine Pitrou63065d72012-05-15 23:48:04 +02005905 if (q == e) {
5906 if (consumed)
5907 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005908 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005909 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005910
Christian Heimes743e0cd2012-10-17 23:52:17 +02005911#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005912 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005913 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005914#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005915 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005916 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005917#endif
Tim Peters772747b2001-08-09 22:21:55 +00005918
Antoine Pitrou63065d72012-05-15 23:48:04 +02005919 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005920 character count normally. Error handler will take care of
5921 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005922 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005923 writer.min_length = (e - q + 1) / 2;
5924 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005925 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005926
Antoine Pitrou63065d72012-05-15 23:48:04 +02005927 while (1) {
5928 Py_UCS4 ch = 0;
5929 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005930 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005931 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005932 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005933 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005934 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005935 native_ordering);
5936 else
5937 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005938 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005939 native_ordering);
5940 } else if (kind == PyUnicode_2BYTE_KIND) {
5941 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005942 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005943 native_ordering);
5944 } else {
5945 assert(kind == PyUnicode_4BYTE_KIND);
5946 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005947 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005948 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005949 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005950 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005951
Antoine Pitrou63065d72012-05-15 23:48:04 +02005952 switch (ch)
5953 {
5954 case 0:
5955 /* remaining byte at the end? (size should be even) */
5956 if (q == e || consumed)
5957 goto End;
5958 errmsg = "truncated data";
5959 startinpos = ((const char *)q) - starts;
5960 endinpos = ((const char *)e) - starts;
5961 break;
5962 /* The remaining input chars are ignored if the callback
5963 chooses to skip the input */
5964 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005965 q -= 2;
5966 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005967 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005968 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005969 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005970 endinpos = ((const char *)e) - starts;
5971 break;
5972 case 2:
5973 errmsg = "illegal encoding";
5974 startinpos = ((const char *)q) - 2 - starts;
5975 endinpos = startinpos + 2;
5976 break;
5977 case 3:
5978 errmsg = "illegal UTF-16 surrogate";
5979 startinpos = ((const char *)q) - 4 - starts;
5980 endinpos = startinpos + 2;
5981 break;
5982 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005983 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005984 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005985 continue;
5986 }
5987
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005988 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005989 errors,
5990 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005991 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005992 &starts,
5993 (const char **)&e,
5994 &startinpos,
5995 &endinpos,
5996 &exc,
5997 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005998 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000 }
6001
Antoine Pitrou63065d72012-05-15 23:48:04 +02006002End:
Walter Dörwald69652032004-09-07 20:24:22 +00006003 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00006005
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006006 Py_XDECREF(errorHandler);
6007 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006008 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009
Benjamin Peterson29060642009-01-31 22:14:21 +00006010 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006011 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006012 Py_XDECREF(errorHandler);
6013 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014 return NULL;
6015}
6016
Tim Peters772747b2001-08-09 22:21:55 +00006017PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006018_PyUnicode_EncodeUTF16(PyObject *str,
6019 const char *errors,
6020 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006022 enum PyUnicode_Kind kind;
6023 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006024 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006025 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006026 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006027 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02006028#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006029 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00006030#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006031 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00006032#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006033 const char *encoding;
6034 Py_ssize_t nsize, pos;
6035 PyObject *errorHandler = NULL;
6036 PyObject *exc = NULL;
6037 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00006038
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006039 if (!PyUnicode_Check(str)) {
6040 PyErr_BadArgument();
6041 return NULL;
6042 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05006043 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006044 return NULL;
6045 kind = PyUnicode_KIND(str);
6046 data = PyUnicode_DATA(str);
6047 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01006048
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006049 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006050 if (kind == PyUnicode_4BYTE_KIND) {
6051 const Py_UCS4 *in = (const Py_UCS4 *)data;
6052 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006053 while (in < end) {
6054 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006055 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006056 }
6057 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006058 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006059 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006060 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006061 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006062 nsize = len + pairs + (byteorder == 0);
6063 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006064 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006065 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006066 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006068 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02006069 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006070 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006071 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02006072 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006073 }
6074 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00006075 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006076 }
Tim Peters772747b2001-08-09 22:21:55 +00006077
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006078 if (kind == PyUnicode_1BYTE_KIND) {
6079 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
6080 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006081 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006082
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006083 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006084 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006085 }
6086 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006087 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006088 }
6089 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006090 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02006091 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006092
6093 pos = 0;
6094 while (pos < len) {
6095 Py_ssize_t repsize, moreunits;
6096
6097 if (kind == PyUnicode_2BYTE_KIND) {
6098 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
6099 &out, native_ordering);
6100 }
6101 else {
6102 assert(kind == PyUnicode_4BYTE_KIND);
6103 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
6104 &out, native_ordering);
6105 }
6106 if (pos == len)
6107 break;
6108
6109 rep = unicode_encode_call_errorhandler(
6110 errors, &errorHandler,
6111 encoding, "surrogates not allowed",
6112 str, &exc, pos, pos + 1, &pos);
6113 if (!rep)
6114 goto error;
6115
6116 if (PyBytes_Check(rep)) {
6117 repsize = PyBytes_GET_SIZE(rep);
6118 if (repsize & 1) {
6119 raise_encode_exception(&exc, encoding,
6120 str, pos - 1, pos,
6121 "surrogates not allowed");
6122 goto error;
6123 }
6124 moreunits = repsize / 2;
6125 }
6126 else {
6127 assert(PyUnicode_Check(rep));
6128 if (PyUnicode_READY(rep) < 0)
6129 goto error;
6130 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
6131 if (!PyUnicode_IS_ASCII(rep)) {
6132 raise_encode_exception(&exc, encoding,
6133 str, pos - 1, pos,
6134 "surrogates not allowed");
6135 goto error;
6136 }
6137 }
6138
6139 /* two bytes are reserved for each surrogate */
6140 if (moreunits > 1) {
6141 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006142 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006143 /* integer overflow */
6144 PyErr_NoMemory();
6145 goto error;
6146 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006147 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006148 goto error;
6149 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
6150 }
6151
6152 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02006153 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006154 out += moreunits;
6155 } else /* rep is unicode */ {
6156 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6157 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
6158 &out, native_ordering);
6159 }
6160
6161 Py_CLEAR(rep);
6162 }
6163
6164 /* Cut back to size actually needed. This is necessary for, for example,
6165 encoding of a string containing isolated surrogates and the 'ignore' handler
6166 is used. */
6167 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
6168 if (nsize != PyBytes_GET_SIZE(v))
6169 _PyBytes_Resize(&v, nsize);
6170 Py_XDECREF(errorHandler);
6171 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00006172 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006173 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02006174 error:
6175 Py_XDECREF(rep);
6176 Py_XDECREF(errorHandler);
6177 Py_XDECREF(exc);
6178 Py_XDECREF(v);
6179 return NULL;
6180#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006181}
6182
Alexander Belopolsky40018472011-02-26 01:02:56 +00006183PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006184PyUnicode_EncodeUTF16(const Py_UNICODE *s,
6185 Py_ssize_t size,
6186 const char *errors,
6187 int byteorder)
6188{
6189 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006190 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006191 if (tmp == NULL)
6192 return NULL;
6193 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
6194 Py_DECREF(tmp);
6195 return result;
6196}
6197
6198PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00006199PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006201 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202}
6203
6204/* --- Unicode Escape Codec ----------------------------------------------- */
6205
Fredrik Lundh06d12682001-01-24 07:59:11 +00006206static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00006207
Alexander Belopolsky40018472011-02-26 01:02:56 +00006208PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04006209_PyUnicode_DecodeUnicodeEscape(const char *s,
6210 Py_ssize_t size,
6211 const char *errors,
6212 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006214 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006215 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006216 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006217 PyObject *errorHandler = NULL;
6218 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006219
Eric V. Smith42454af2016-10-31 09:22:08 -04006220 // so we can remember if we've seen an invalid escape char or not
6221 *first_invalid_escape = NULL;
6222
Victor Stinner62ec3312016-09-06 17:04:34 -07006223 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006224 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006225 }
6226 /* Escaped strings will always be longer than the resulting
6227 Unicode string, so we start with size here and then reduce the
6228 length after conversion to the true value.
6229 (but if the error callback returns a long replacement string
6230 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006231 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006232 writer.min_length = size;
6233 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6234 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006235 }
6236
Guido van Rossumd57fd912000-03-10 22:53:23 +00006237 end = s + size;
6238 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006239 unsigned char c = (unsigned char) *s++;
6240 Py_UCS4 ch;
6241 int count;
6242 Py_ssize_t startinpos;
6243 Py_ssize_t endinpos;
6244 const char *message;
6245
6246#define WRITE_ASCII_CHAR(ch) \
6247 do { \
6248 assert(ch <= 127); \
6249 assert(writer.pos < writer.size); \
6250 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6251 } while(0)
6252
6253#define WRITE_CHAR(ch) \
6254 do { \
6255 if (ch <= writer.maxchar) { \
6256 assert(writer.pos < writer.size); \
6257 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6258 } \
6259 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6260 goto onError; \
6261 } \
6262 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006263
6264 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006265 if (c != '\\') {
6266 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006267 continue;
6268 }
6269
Victor Stinner62ec3312016-09-06 17:04:34 -07006270 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006271 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006272 if (s >= end) {
6273 message = "\\ at end of string";
6274 goto error;
6275 }
6276 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006277
Victor Stinner62ec3312016-09-06 17:04:34 -07006278 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006279 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006280
Benjamin Peterson29060642009-01-31 22:14:21 +00006281 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006282 case '\n': continue;
6283 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6284 case '\'': WRITE_ASCII_CHAR('\''); continue;
6285 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6286 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006287 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006288 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6289 case 't': WRITE_ASCII_CHAR('\t'); continue;
6290 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6291 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006292 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006293 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006294 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006295 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296
Benjamin Peterson29060642009-01-31 22:14:21 +00006297 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006298 case '0': case '1': case '2': case '3':
6299 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006300 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006301 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006302 ch = (ch<<3) + *s++ - '0';
6303 if (s < end && '0' <= *s && *s <= '7') {
6304 ch = (ch<<3) + *s++ - '0';
6305 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006306 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006307 WRITE_CHAR(ch);
6308 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006309
Benjamin Peterson29060642009-01-31 22:14:21 +00006310 /* hex escapes */
6311 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006312 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006313 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006314 message = "truncated \\xXX escape";
6315 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006316
Benjamin Peterson29060642009-01-31 22:14:21 +00006317 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006318 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006319 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006320 message = "truncated \\uXXXX escape";
6321 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006322
Benjamin Peterson29060642009-01-31 22:14:21 +00006323 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006324 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006325 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006326 message = "truncated \\UXXXXXXXX escape";
6327 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006328 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006329 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006330 ch <<= 4;
6331 if (c >= '0' && c <= '9') {
6332 ch += c - '0';
6333 }
6334 else if (c >= 'a' && c <= 'f') {
6335 ch += c - ('a' - 10);
6336 }
6337 else if (c >= 'A' && c <= 'F') {
6338 ch += c - ('A' - 10);
6339 }
6340 else {
6341 break;
6342 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006343 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006344 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006345 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006346 }
6347
6348 /* when we get here, ch is a 32-bit unicode character */
6349 if (ch > MAX_UNICODE) {
6350 message = "illegal Unicode character";
6351 goto error;
6352 }
6353
6354 WRITE_CHAR(ch);
6355 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006356
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006358 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006359 if (ucnhash_CAPI == NULL) {
6360 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006361 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6362 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006363 if (ucnhash_CAPI == NULL) {
6364 PyErr_SetString(
6365 PyExc_UnicodeError,
6366 "\\N escapes not supported (can't load unicodedata module)"
6367 );
6368 goto onError;
6369 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006370 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006371
6372 message = "malformed \\N character escape";
Gregory P. Smith746b2d32018-11-13 13:16:54 -08006373 if (s < end && *s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006374 const char *start = ++s;
6375 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006376 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006377 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006378 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006379 namelen = s - start;
6380 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006381 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006382 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006383 ch = 0xffffffff; /* in case 'getcode' messes up */
6384 if (namelen <= INT_MAX &&
6385 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6386 &ch, 0)) {
6387 assert(ch <= MAX_UNICODE);
6388 WRITE_CHAR(ch);
6389 continue;
6390 }
6391 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006392 }
6393 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006394 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006395
6396 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006397 if (*first_invalid_escape == NULL) {
6398 *first_invalid_escape = s-1; /* Back up one char, since we've
6399 already incremented s. */
6400 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006401 WRITE_ASCII_CHAR('\\');
6402 WRITE_CHAR(c);
6403 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006404 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006405
6406 error:
6407 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006408 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006409 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006410 errors, &errorHandler,
6411 "unicodeescape", message,
6412 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006413 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006414 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006415 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006416 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006417
6418#undef WRITE_ASCII_CHAR
6419#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006420 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006421
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006422 Py_XDECREF(errorHandler);
6423 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006424 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006425
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006427 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428 Py_XDECREF(errorHandler);
6429 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006430 return NULL;
6431}
6432
Eric V. Smith42454af2016-10-31 09:22:08 -04006433PyObject *
6434PyUnicode_DecodeUnicodeEscape(const char *s,
6435 Py_ssize_t size,
6436 const char *errors)
6437{
6438 const char *first_invalid_escape;
6439 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6440 &first_invalid_escape);
6441 if (result == NULL)
6442 return NULL;
6443 if (first_invalid_escape != NULL) {
6444 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6445 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006446 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006447 Py_DECREF(result);
6448 return NULL;
6449 }
6450 }
6451 return result;
6452}
6453
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006454/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006455
Alexander Belopolsky40018472011-02-26 01:02:56 +00006456PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006457PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006458{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006459 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006460 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006461 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006462 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03006463 const void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006464 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006465
Ezio Melottie7f90372012-10-05 03:33:31 +03006466 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006467 escape.
6468
Ezio Melottie7f90372012-10-05 03:33:31 +03006469 For UCS1 strings it's '\xxx', 4 bytes per source character.
6470 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6471 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006472 */
6473
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006474 if (!PyUnicode_Check(unicode)) {
6475 PyErr_BadArgument();
6476 return NULL;
6477 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006478 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006479 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006480 }
Victor Stinner358af132015-10-12 22:36:57 +02006481
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006482 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006483 if (len == 0) {
6484 return PyBytes_FromStringAndSize(NULL, 0);
6485 }
6486
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006487 kind = PyUnicode_KIND(unicode);
6488 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006489 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6490 bytes, and 1 byte characters 4. */
6491 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006492 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006493 return PyErr_NoMemory();
6494 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006495 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006496 if (repr == NULL) {
6497 return NULL;
6498 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006499
Victor Stinner62ec3312016-09-06 17:04:34 -07006500 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006501 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006502 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006503
Victor Stinner62ec3312016-09-06 17:04:34 -07006504 /* U+0000-U+00ff range */
6505 if (ch < 0x100) {
6506 if (ch >= ' ' && ch < 127) {
6507 if (ch != '\\') {
6508 /* Copy printable US ASCII as-is */
6509 *p++ = (char) ch;
6510 }
6511 /* Escape backslashes */
6512 else {
6513 *p++ = '\\';
6514 *p++ = '\\';
6515 }
6516 }
Victor Stinner358af132015-10-12 22:36:57 +02006517
Victor Stinner62ec3312016-09-06 17:04:34 -07006518 /* Map special whitespace to '\t', \n', '\r' */
6519 else if (ch == '\t') {
6520 *p++ = '\\';
6521 *p++ = 't';
6522 }
6523 else if (ch == '\n') {
6524 *p++ = '\\';
6525 *p++ = 'n';
6526 }
6527 else if (ch == '\r') {
6528 *p++ = '\\';
6529 *p++ = 'r';
6530 }
6531
6532 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6533 else {
6534 *p++ = '\\';
6535 *p++ = 'x';
6536 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6537 *p++ = Py_hexdigits[ch & 0x000F];
6538 }
Tim Petersced69f82003-09-16 20:30:58 +00006539 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006540 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006541 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006542 *p++ = '\\';
6543 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006544 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6545 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6546 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6547 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006548 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006549 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6550 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006551
Victor Stinner62ec3312016-09-06 17:04:34 -07006552 /* Make sure that the first two digits are zero */
6553 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006554 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006555 *p++ = 'U';
6556 *p++ = '0';
6557 *p++ = '0';
6558 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6559 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6560 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6561 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6562 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6563 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006564 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006565 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006566
Victor Stinner62ec3312016-09-06 17:04:34 -07006567 assert(p - PyBytes_AS_STRING(repr) > 0);
6568 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6569 return NULL;
6570 }
6571 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006572}
6573
Alexander Belopolsky40018472011-02-26 01:02:56 +00006574PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006575PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6576 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006577{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006578 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006579 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006580 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006581 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006582 }
6583
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006584 result = PyUnicode_AsUnicodeEscapeString(tmp);
6585 Py_DECREF(tmp);
6586 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006587}
6588
6589/* --- Raw Unicode Escape Codec ------------------------------------------- */
6590
Alexander Belopolsky40018472011-02-26 01:02:56 +00006591PyObject *
6592PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006593 Py_ssize_t size,
6594 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006595{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006597 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006598 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599 PyObject *errorHandler = NULL;
6600 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006601
Victor Stinner62ec3312016-09-06 17:04:34 -07006602 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006603 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006604 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006605
Guido van Rossumd57fd912000-03-10 22:53:23 +00006606 /* Escaped strings will always be longer than the resulting
6607 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006608 length after conversion to the true value. (But decoding error
6609 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006610 _PyUnicodeWriter_Init(&writer);
Inada Naoki770847a2019-06-24 12:30:24 +09006611 writer.min_length = size;
Victor Stinner62ec3312016-09-06 17:04:34 -07006612 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6613 goto onError;
6614 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006615
Guido van Rossumd57fd912000-03-10 22:53:23 +00006616 end = s + size;
6617 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006618 unsigned char c = (unsigned char) *s++;
6619 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006620 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006621 Py_ssize_t startinpos;
6622 Py_ssize_t endinpos;
6623 const char *message;
6624
6625#define WRITE_CHAR(ch) \
6626 do { \
6627 if (ch <= writer.maxchar) { \
6628 assert(writer.pos < writer.size); \
6629 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6630 } \
6631 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6632 goto onError; \
6633 } \
6634 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006637 if (c != '\\' || s >= end) {
6638 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006639 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006640 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006641
Victor Stinner62ec3312016-09-06 17:04:34 -07006642 c = (unsigned char) *s++;
6643 if (c == 'u') {
6644 count = 4;
6645 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006646 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006647 else if (c == 'U') {
6648 count = 8;
6649 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006650 }
6651 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006652 assert(writer.pos < writer.size);
6653 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6654 WRITE_CHAR(c);
6655 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006656 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006657 startinpos = s - starts - 2;
6658
6659 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6660 for (ch = 0; count && s < end; ++s, --count) {
6661 c = (unsigned char)*s;
6662 ch <<= 4;
6663 if (c >= '0' && c <= '9') {
6664 ch += c - '0';
6665 }
6666 else if (c >= 'a' && c <= 'f') {
6667 ch += c - ('a' - 10);
6668 }
6669 else if (c >= 'A' && c <= 'F') {
6670 ch += c - ('A' - 10);
6671 }
6672 else {
6673 break;
6674 }
6675 }
6676 if (!count) {
6677 if (ch <= MAX_UNICODE) {
6678 WRITE_CHAR(ch);
6679 continue;
6680 }
6681 message = "\\Uxxxxxxxx out of range";
6682 }
6683
6684 endinpos = s-starts;
6685 writer.min_length = end - s + writer.pos;
6686 if (unicode_decode_call_errorhandler_writer(
6687 errors, &errorHandler,
6688 "rawunicodeescape", message,
6689 &starts, &end, &startinpos, &endinpos, &exc, &s,
6690 &writer)) {
6691 goto onError;
6692 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006693 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006694
6695#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006696 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697 Py_XDECREF(errorHandler);
6698 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006699 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006700
Benjamin Peterson29060642009-01-31 22:14:21 +00006701 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006702 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006703 Py_XDECREF(errorHandler);
6704 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006705 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006706
Guido van Rossumd57fd912000-03-10 22:53:23 +00006707}
6708
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006709
Alexander Belopolsky40018472011-02-26 01:02:56 +00006710PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006711PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006712{
Victor Stinner62ec3312016-09-06 17:04:34 -07006713 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006714 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006715 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006716 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03006717 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006718 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006719
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006720 if (!PyUnicode_Check(unicode)) {
6721 PyErr_BadArgument();
6722 return NULL;
6723 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006724 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006725 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006726 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006727 kind = PyUnicode_KIND(unicode);
6728 data = PyUnicode_DATA(unicode);
6729 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006730 if (kind == PyUnicode_1BYTE_KIND) {
6731 return PyBytes_FromStringAndSize(data, len);
6732 }
Victor Stinner0e368262011-11-10 20:12:49 +01006733
Victor Stinner62ec3312016-09-06 17:04:34 -07006734 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6735 bytes, and 1 byte characters 4. */
6736 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006737
Victor Stinner62ec3312016-09-06 17:04:34 -07006738 if (len > PY_SSIZE_T_MAX / expandsize) {
6739 return PyErr_NoMemory();
6740 }
6741 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6742 if (repr == NULL) {
6743 return NULL;
6744 }
6745 if (len == 0) {
6746 return repr;
6747 }
6748
6749 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006750 for (pos = 0; pos < len; pos++) {
6751 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006752
Victor Stinner62ec3312016-09-06 17:04:34 -07006753 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6754 if (ch < 0x100) {
6755 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006756 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006757 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006758 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759 *p++ = '\\';
6760 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006761 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6762 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6763 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6764 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006765 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006766 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6767 else {
6768 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6769 *p++ = '\\';
6770 *p++ = 'U';
6771 *p++ = '0';
6772 *p++ = '0';
6773 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6774 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6775 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6776 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6777 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6778 *p++ = Py_hexdigits[ch & 15];
6779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006780 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006781
Victor Stinner62ec3312016-09-06 17:04:34 -07006782 assert(p > PyBytes_AS_STRING(repr));
6783 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6784 return NULL;
6785 }
6786 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006787}
6788
Alexander Belopolsky40018472011-02-26 01:02:56 +00006789PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006790PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6791 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006792{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006793 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006794 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006795 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006796 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006797 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6798 Py_DECREF(tmp);
6799 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006800}
6801
6802/* --- Latin-1 Codec ------------------------------------------------------ */
6803
Alexander Belopolsky40018472011-02-26 01:02:56 +00006804PyObject *
6805PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006806 Py_ssize_t size,
6807 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006808{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006809 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Andy Lestere6be9b52020-02-11 20:28:35 -06006810 return _PyUnicode_FromUCS1((const unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006811}
6812
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006813/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006814static void
6815make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006816 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006817 PyObject *unicode,
6818 Py_ssize_t startpos, Py_ssize_t endpos,
6819 const char *reason)
6820{
6821 if (*exceptionObject == NULL) {
6822 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006823 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006824 encoding, unicode, startpos, endpos, reason);
6825 }
6826 else {
6827 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6828 goto onError;
6829 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6830 goto onError;
6831 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6832 goto onError;
6833 return;
6834 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006835 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006836 }
6837}
6838
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006839/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006840static void
6841raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006842 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006843 PyObject *unicode,
6844 Py_ssize_t startpos, Py_ssize_t endpos,
6845 const char *reason)
6846{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006847 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006848 encoding, unicode, startpos, endpos, reason);
6849 if (*exceptionObject != NULL)
6850 PyCodec_StrictErrors(*exceptionObject);
6851}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006852
6853/* error handling callback helper:
6854 build arguments, call the callback and check the arguments,
6855 put the result into newpos and return the replacement string, which
6856 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006857static PyObject *
6858unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006859 PyObject **errorHandler,
6860 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006861 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006862 Py_ssize_t startpos, Py_ssize_t endpos,
6863 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006864{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006865 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006866 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006867 PyObject *restuple;
6868 PyObject *resunicode;
6869
6870 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006871 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006872 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006873 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006874 }
6875
Benjamin Petersonbac79492012-01-14 13:34:47 -05006876 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006877 return NULL;
6878 len = PyUnicode_GET_LENGTH(unicode);
6879
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006880 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006881 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006882 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006883 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006884
Petr Viktorinffd97532020-02-11 17:46:57 +01006885 restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006886 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006887 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006888 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006889 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006890 Py_DECREF(restuple);
6891 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006892 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006893 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006894 &resunicode, newpos)) {
6895 Py_DECREF(restuple);
6896 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006897 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006898 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6899 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6900 Py_DECREF(restuple);
6901 return NULL;
6902 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006903 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006904 *newpos = len + *newpos;
6905 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006906 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006907 Py_DECREF(restuple);
6908 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006909 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006910 Py_INCREF(resunicode);
6911 Py_DECREF(restuple);
6912 return resunicode;
6913}
6914
Alexander Belopolsky40018472011-02-26 01:02:56 +00006915static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006916unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006917 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006918 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006919{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006920 /* input state */
6921 Py_ssize_t pos=0, size;
6922 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03006923 const void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006924 /* pointer into the output */
6925 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006926 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6927 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006928 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006929 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006930 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006931 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006932 /* output object */
6933 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006934
Benjamin Petersonbac79492012-01-14 13:34:47 -05006935 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006936 return NULL;
6937 size = PyUnicode_GET_LENGTH(unicode);
6938 kind = PyUnicode_KIND(unicode);
6939 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006940 /* allocate enough for a simple encoding without
6941 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006942 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006943 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006944
6945 _PyBytesWriter_Init(&writer);
6946 str = _PyBytesWriter_Alloc(&writer, size);
6947 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006948 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006949
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006950 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006951 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006952
Benjamin Peterson29060642009-01-31 22:14:21 +00006953 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006954 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006955 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006956 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006957 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006958 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006959 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006960 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006961 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006962 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006963 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006964 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006965
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006966 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006967 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006968
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006969 /* Only overallocate the buffer if it's not the last write */
6970 writer.overallocate = (collend < size);
6971
Benjamin Peterson29060642009-01-31 22:14:21 +00006972 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006973 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006974 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02006975
6976 switch (error_handler) {
6977 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006978 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006979 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006980
6981 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006982 memset(str, '?', collend - collstart);
6983 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006984 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006985 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006986 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 break;
Victor Stinner50149202015-09-22 00:26:54 +02006988
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006989 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006990 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006991 writer.min_size -= (collend - collstart);
6992 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006993 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006994 if (str == NULL)
6995 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006996 pos = collend;
6997 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006998
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006999 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07007000 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02007001 writer.min_size -= (collend - collstart);
7002 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02007003 unicode, collstart, collend);
7004 if (str == NULL)
7005 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007006 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 break;
Victor Stinner50149202015-09-22 00:26:54 +02007008
Victor Stinnerc3713e92015-09-29 12:32:13 +02007009 case _Py_ERROR_SURROGATEESCAPE:
7010 for (i = collstart; i < collend; ++i) {
7011 ch = PyUnicode_READ(kind, data, i);
7012 if (ch < 0xdc80 || 0xdcff < ch) {
7013 /* Not a UTF-8b surrogate */
7014 break;
7015 }
7016 *str++ = (char)(ch - 0xdc00);
7017 ++pos;
7018 }
7019 if (i >= collend)
7020 break;
7021 collstart = pos;
7022 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02007023 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02007024
Benjamin Peterson29060642009-01-31 22:14:21 +00007025 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02007026 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
7027 encoding, reason, unicode, &exc,
7028 collstart, collend, &newpos);
7029 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007030 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02007031
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07007032 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08007033 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02007034
Victor Stinner6bd525b2015-10-09 13:10:05 +02007035 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00007036 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02007037 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02007038 PyBytes_AS_STRING(rep),
7039 PyBytes_GET_SIZE(rep));
Martin v. Löwisdb12d452009-05-02 18:52:14 +00007040 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02007041 else {
7042 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02007043
Victor Stinner6bd525b2015-10-09 13:10:05 +02007044 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007045 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02007046
Serhiy Storchaka99250d52016-11-23 15:13:00 +02007047 if (limit == 256 ?
7048 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
7049 !PyUnicode_IS_ASCII(rep))
7050 {
7051 /* Not all characters are smaller than limit */
7052 raise_encode_exception(&exc, encoding, unicode,
7053 collstart, collend, reason);
7054 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007055 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02007056 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
7057 str = _PyBytesWriter_WriteBytes(&writer, str,
7058 PyUnicode_DATA(rep),
7059 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00007060 }
Alexey Izbyshev74a307d2018-08-19 21:52:04 +03007061 if (str == NULL)
7062 goto onError;
7063
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007064 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02007065 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007066 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007067
7068 /* If overallocation was disabled, ensure that it was the last
7069 write. Otherwise, we missed an optimization */
7070 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007071 }
7072 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007073
Victor Stinner50149202015-09-22 00:26:54 +02007074 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007075 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007076 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007077
7078 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02007079 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02007080 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02007081 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00007082 Py_XDECREF(exc);
7083 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007084}
7085
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007086/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007087PyObject *
7088PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03007089 Py_ssize_t size,
7090 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007091{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007092 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007093 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007094 if (unicode == NULL)
7095 return NULL;
7096 result = unicode_encode_ucs1(unicode, errors, 256);
7097 Py_DECREF(unicode);
7098 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007099}
7100
Alexander Belopolsky40018472011-02-26 01:02:56 +00007101PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007102_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007103{
7104 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007105 PyErr_BadArgument();
7106 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007107 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007108 if (PyUnicode_READY(unicode) == -1)
7109 return NULL;
7110 /* Fast path: if it is a one-byte string, construct
7111 bytes object directly. */
7112 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
7113 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7114 PyUnicode_GET_LENGTH(unicode));
7115 /* Non-Latin-1 characters present. Defer to above function to
7116 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007117 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007118}
7119
7120PyObject*
7121PyUnicode_AsLatin1String(PyObject *unicode)
7122{
7123 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007124}
7125
7126/* --- 7-bit ASCII Codec -------------------------------------------------- */
7127
Alexander Belopolsky40018472011-02-26 01:02:56 +00007128PyObject *
7129PyUnicode_DecodeASCII(const char *s,
7130 Py_ssize_t size,
7131 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007132{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007133 const char *starts = s;
Inada Naoki770847a2019-06-24 12:30:24 +09007134 const char *e = s + size;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007135 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007136 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007137 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00007138
Guido van Rossumd57fd912000-03-10 22:53:23 +00007139 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02007140 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007141
Guido van Rossumd57fd912000-03-10 22:53:23 +00007142 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02007143 if (size == 1 && (unsigned char)s[0] < 128)
7144 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007145
Inada Naoki770847a2019-06-24 12:30:24 +09007146 // Shortcut for simple case
7147 PyObject *u = PyUnicode_New(size, 127);
7148 if (u == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02007149 return NULL;
Inada Naoki770847a2019-06-24 12:30:24 +09007150 }
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03007151 Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
Inada Naoki770847a2019-06-24 12:30:24 +09007152 if (outpos == size) {
7153 return u;
7154 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007155
Inada Naoki770847a2019-06-24 12:30:24 +09007156 _PyUnicodeWriter writer;
7157 _PyUnicodeWriter_InitWithBuffer(&writer, u);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007158 writer.pos = outpos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02007159
Inada Naoki770847a2019-06-24 12:30:24 +09007160 s += outpos;
7161 int kind = writer.kind;
7162 void *data = writer.data;
7163 Py_ssize_t startinpos, endinpos;
7164
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007165 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007166 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007167 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007168 PyUnicode_WRITE(kind, data, writer.pos, c);
7169 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007170 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007171 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007172 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007173
7174 /* byte outsize range 0x00..0x7f: call the error handler */
7175
7176 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02007177 error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007178
7179 switch (error_handler)
7180 {
7181 case _Py_ERROR_REPLACE:
7182 case _Py_ERROR_SURROGATEESCAPE:
7183 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007184 but we may switch to UCS2 at the first write */
7185 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7186 goto onError;
7187 kind = writer.kind;
7188 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007189
7190 if (error_handler == _Py_ERROR_REPLACE)
7191 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7192 else
7193 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7194 writer.pos++;
7195 ++s;
7196 break;
7197
7198 case _Py_ERROR_IGNORE:
7199 ++s;
7200 break;
7201
7202 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007203 startinpos = s-starts;
7204 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007205 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007206 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007207 "ascii", "ordinal not in range(128)",
7208 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007209 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007210 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007211 kind = writer.kind;
7212 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007213 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007214 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007215 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007216 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007217 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007218
Benjamin Peterson29060642009-01-31 22:14:21 +00007219 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007220 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007221 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007222 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007223 return NULL;
7224}
7225
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007226/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007227PyObject *
7228PyUnicode_EncodeASCII(const Py_UNICODE *p,
7229 Py_ssize_t size,
7230 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007231{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007232 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007233 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007234 if (unicode == NULL)
7235 return NULL;
7236 result = unicode_encode_ucs1(unicode, errors, 128);
7237 Py_DECREF(unicode);
7238 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007239}
7240
Alexander Belopolsky40018472011-02-26 01:02:56 +00007241PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007242_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007243{
7244 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007245 PyErr_BadArgument();
7246 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007248 if (PyUnicode_READY(unicode) == -1)
7249 return NULL;
7250 /* Fast path: if it is an ASCII-only string, construct bytes object
7251 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007252 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007253 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7254 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007255 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007256}
7257
7258PyObject *
7259PyUnicode_AsASCIIString(PyObject *unicode)
7260{
7261 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007262}
7263
Steve Dowercc16be82016-09-08 10:35:16 -07007264#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007265
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007266/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007267
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007268#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007269#define NEED_RETRY
7270#endif
7271
Steve Dower7ebdda02019-08-21 16:22:33 -07007272/* INT_MAX is the theoretical largest chunk (or INT_MAX / 2 when
7273 transcoding from UTF-16), but INT_MAX / 4 perfoms better in
7274 both cases also and avoids partial characters overrunning the
7275 length limit in MultiByteToWideChar on Windows */
7276#define DECODING_CHUNK_SIZE (INT_MAX/4)
7277
Victor Stinner3a50e702011-10-18 21:21:00 +02007278#ifndef WC_ERR_INVALID_CHARS
7279# define WC_ERR_INVALID_CHARS 0x0080
7280#endif
7281
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007282static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007283code_page_name(UINT code_page, PyObject **obj)
7284{
7285 *obj = NULL;
7286 if (code_page == CP_ACP)
7287 return "mbcs";
7288 if (code_page == CP_UTF7)
7289 return "CP_UTF7";
7290 if (code_page == CP_UTF8)
7291 return "CP_UTF8";
7292
7293 *obj = PyBytes_FromFormat("cp%u", code_page);
7294 if (*obj == NULL)
7295 return NULL;
7296 return PyBytes_AS_STRING(*obj);
7297}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007298
Victor Stinner3a50e702011-10-18 21:21:00 +02007299static DWORD
7300decode_code_page_flags(UINT code_page)
7301{
7302 if (code_page == CP_UTF7) {
7303 /* The CP_UTF7 decoder only supports flags=0 */
7304 return 0;
7305 }
7306 else
7307 return MB_ERR_INVALID_CHARS;
7308}
7309
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007310/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007311 * Decode a byte string from a Windows code page into unicode object in strict
7312 * mode.
7313 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007314 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7315 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007316 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007317static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007318decode_code_page_strict(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007319 wchar_t **buf,
7320 Py_ssize_t *bufsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 const char *in,
7322 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007323{
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007324 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner24729f32011-11-10 20:31:37 +01007325 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007326 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007327
7328 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007329 assert(insize > 0);
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007330 while ((outsize = MultiByteToWideChar(code_page, flags,
7331 in, insize, NULL, 0)) <= 0)
7332 {
7333 if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
7334 goto error;
7335 }
7336 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7337 flags = 0;
7338 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007339
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007340 /* Extend a wchar_t* buffer */
7341 Py_ssize_t n = *bufsize; /* Get the current length */
7342 if (widechar_resize(buf, bufsize, n + outsize) < 0) {
7343 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007344 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007345 out = *buf + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007346
7347 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007348 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7349 if (outsize <= 0)
7350 goto error;
7351 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007352
Victor Stinner3a50e702011-10-18 21:21:00 +02007353error:
7354 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7355 return -2;
7356 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007357 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007358}
7359
Victor Stinner3a50e702011-10-18 21:21:00 +02007360/*
7361 * Decode a byte string from a code page into unicode object with an error
7362 * handler.
7363 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007364 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007365 * UnicodeDecodeError exception and returns -1 on error.
7366 */
7367static int
7368decode_code_page_errors(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007369 wchar_t **buf,
7370 Py_ssize_t *bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007371 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007372 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007373{
7374 const char *startin = in;
7375 const char *endin = in + size;
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007376 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007377 /* Ideally, we should get reason from FormatMessage. This is the Windows
7378 2000 English version of the message. */
7379 const char *reason = "No mapping for the Unicode character exists "
7380 "in the target code page.";
7381 /* each step cannot decode more than 1 character, but a character can be
7382 represented as a surrogate pair */
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007383 wchar_t buffer[2], *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007384 int insize;
7385 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007386 PyObject *errorHandler = NULL;
7387 PyObject *exc = NULL;
7388 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007389 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 DWORD err;
7391 int ret = -1;
7392
7393 assert(size > 0);
7394
7395 encoding = code_page_name(code_page, &encoding_obj);
7396 if (encoding == NULL)
7397 return -1;
7398
Victor Stinner7d00cc12014-03-17 23:08:06 +01007399 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007400 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7401 UnicodeDecodeError. */
7402 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7403 if (exc != NULL) {
7404 PyCodec_StrictErrors(exc);
7405 Py_CLEAR(exc);
7406 }
7407 goto error;
7408 }
7409
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007410 /* Extend a wchar_t* buffer */
7411 Py_ssize_t n = *bufsize; /* Get the current length */
7412 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7413 PyErr_NoMemory();
7414 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007416 if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
7417 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007419 out = *buf + n;
Victor Stinner3a50e702011-10-18 21:21:00 +02007420
7421 /* Decode the byte string character per character */
Victor Stinner3a50e702011-10-18 21:21:00 +02007422 while (in < endin)
7423 {
7424 /* Decode a character */
7425 insize = 1;
7426 do
7427 {
7428 outsize = MultiByteToWideChar(code_page, flags,
7429 in, insize,
7430 buffer, Py_ARRAY_LENGTH(buffer));
7431 if (outsize > 0)
7432 break;
7433 err = GetLastError();
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007434 if (err == ERROR_INVALID_FLAGS && flags) {
7435 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7436 flags = 0;
7437 continue;
7438 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 if (err != ERROR_NO_UNICODE_TRANSLATION
7440 && err != ERROR_INSUFFICIENT_BUFFER)
7441 {
7442 PyErr_SetFromWindowsErr(0);
7443 goto error;
7444 }
7445 insize++;
7446 }
7447 /* 4=maximum length of a UTF-8 sequence */
7448 while (insize <= 4 && (in + insize) <= endin);
7449
7450 if (outsize <= 0) {
7451 Py_ssize_t startinpos, endinpos, outpos;
7452
Victor Stinner7d00cc12014-03-17 23:08:06 +01007453 /* last character in partial decode? */
7454 if (in + insize >= endin && !final)
7455 break;
7456
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 startinpos = in - startin;
7458 endinpos = startinpos + 1;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007459 outpos = out - *buf;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007460 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007461 errors, &errorHandler,
7462 encoding, reason,
7463 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007464 buf, bufsize, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007465 {
7466 goto error;
7467 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007468 out = *buf + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007469 }
7470 else {
7471 in += insize;
7472 memcpy(out, buffer, outsize * sizeof(wchar_t));
7473 out += outsize;
7474 }
7475 }
7476
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007477 /* Shrink the buffer */
7478 assert(out - *buf <= *bufsize);
7479 *bufsize = out - *buf;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007480 /* (in - startin) <= size and size is an int */
7481 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007482
7483error:
7484 Py_XDECREF(encoding_obj);
7485 Py_XDECREF(errorHandler);
7486 Py_XDECREF(exc);
7487 return ret;
7488}
7489
Victor Stinner3a50e702011-10-18 21:21:00 +02007490static PyObject *
7491decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007492 const char *s, Py_ssize_t size,
7493 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007494{
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007495 wchar_t *buf = NULL;
7496 Py_ssize_t bufsize = 0;
Victor Stinner76a31a62011-11-04 00:05:13 +01007497 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007498
Victor Stinner3a50e702011-10-18 21:21:00 +02007499 if (code_page < 0) {
7500 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7501 return NULL;
7502 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007503 if (size < 0) {
7504 PyErr_BadInternalCall();
7505 return NULL;
7506 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007507
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007508 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007509 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007510
Victor Stinner76a31a62011-11-04 00:05:13 +01007511 do
7512 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007513#ifdef NEED_RETRY
Steve Dower7ebdda02019-08-21 16:22:33 -07007514 if (size > DECODING_CHUNK_SIZE) {
7515 chunk_size = DECODING_CHUNK_SIZE;
Victor Stinner76a31a62011-11-04 00:05:13 +01007516 final = 0;
7517 done = 0;
7518 }
7519 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007520#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007521 {
7522 chunk_size = (int)size;
7523 final = (consumed == NULL);
7524 done = 1;
7525 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007526
Victor Stinner76a31a62011-11-04 00:05:13 +01007527 if (chunk_size == 0 && done) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007528 if (buf != NULL)
Victor Stinner76a31a62011-11-04 00:05:13 +01007529 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007530 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007531 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007532
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007533 converted = decode_code_page_strict(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007534 s, chunk_size);
7535 if (converted == -2)
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007536 converted = decode_code_page_errors(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007537 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007538 errors, final);
7539 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007540
7541 if (converted < 0) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007542 PyMem_Free(buf);
Victor Stinner76a31a62011-11-04 00:05:13 +01007543 return NULL;
7544 }
7545
7546 if (consumed)
7547 *consumed += converted;
7548
7549 s += converted;
7550 size -= converted;
7551 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007552
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007553 PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
7554 PyMem_Free(buf);
7555 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007556}
7557
Alexander Belopolsky40018472011-02-26 01:02:56 +00007558PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007559PyUnicode_DecodeCodePageStateful(int code_page,
7560 const char *s,
7561 Py_ssize_t size,
7562 const char *errors,
7563 Py_ssize_t *consumed)
7564{
7565 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7566}
7567
7568PyObject *
7569PyUnicode_DecodeMBCSStateful(const char *s,
7570 Py_ssize_t size,
7571 const char *errors,
7572 Py_ssize_t *consumed)
7573{
7574 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7575}
7576
7577PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007578PyUnicode_DecodeMBCS(const char *s,
7579 Py_ssize_t size,
7580 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007581{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007582 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7583}
7584
Victor Stinner3a50e702011-10-18 21:21:00 +02007585static DWORD
7586encode_code_page_flags(UINT code_page, const char *errors)
7587{
7588 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007589 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007590 }
7591 else if (code_page == CP_UTF7) {
7592 /* CP_UTF7 only supports flags=0 */
7593 return 0;
7594 }
7595 else {
7596 if (errors != NULL && strcmp(errors, "replace") == 0)
7597 return 0;
7598 else
7599 return WC_NO_BEST_FIT_CHARS;
7600 }
7601}
7602
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007603/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007604 * Encode a Unicode string to a Windows code page into a byte string in strict
7605 * mode.
7606 *
7607 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007608 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007609 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007610static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007611encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007612 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007613 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007614{
Victor Stinner554f3f02010-06-16 23:33:54 +00007615 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007616 BOOL *pusedDefaultChar = &usedDefaultChar;
7617 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007618 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007619 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007620 const DWORD flags = encode_code_page_flags(code_page, NULL);
7621 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007622 /* Create a substring so that we can get the UTF-16 representation
7623 of just the slice under consideration. */
7624 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007625
Martin v. Löwis3d325192011-11-04 18:23:06 +01007626 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007627
Victor Stinner3a50e702011-10-18 21:21:00 +02007628 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007629 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007630 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007631 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007632
Victor Stinner2fc507f2011-11-04 20:06:39 +01007633 substring = PyUnicode_Substring(unicode, offset, offset+len);
7634 if (substring == NULL)
7635 return -1;
7636 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7637 if (p == NULL) {
7638 Py_DECREF(substring);
7639 return -1;
7640 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007641 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007642
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007643 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007644 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007645 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007646 NULL, 0,
7647 NULL, pusedDefaultChar);
7648 if (outsize <= 0)
7649 goto error;
7650 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007651 if (pusedDefaultChar && *pusedDefaultChar) {
7652 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007653 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007654 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007655
Victor Stinner3a50e702011-10-18 21:21:00 +02007656 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007657 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007659 if (*outbytes == NULL) {
7660 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007661 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007662 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007663 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007664 }
7665 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007666 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007667 const Py_ssize_t n = PyBytes_Size(*outbytes);
7668 if (outsize > PY_SSIZE_T_MAX - n) {
7669 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007670 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007671 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007672 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007673 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7674 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007675 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007676 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007677 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007678 }
7679
7680 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007681 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007682 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007683 out, outsize,
7684 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007685 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007686 if (outsize <= 0)
7687 goto error;
7688 if (pusedDefaultChar && *pusedDefaultChar)
7689 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007690 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007691
Victor Stinner3a50e702011-10-18 21:21:00 +02007692error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007693 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007694 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7695 return -2;
7696 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007697 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007698}
7699
Victor Stinner3a50e702011-10-18 21:21:00 +02007700/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007701 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007702 * error handler.
7703 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007704 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007705 * -1 on other error.
7706 */
7707static int
7708encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007709 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007710 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007711{
Victor Stinner3a50e702011-10-18 21:21:00 +02007712 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007713 Py_ssize_t pos = unicode_offset;
7714 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007715 /* Ideally, we should get reason from FormatMessage. This is the Windows
7716 2000 English version of the message. */
7717 const char *reason = "invalid character";
7718 /* 4=maximum length of a UTF-8 sequence */
7719 char buffer[4];
7720 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7721 Py_ssize_t outsize;
7722 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007723 PyObject *errorHandler = NULL;
7724 PyObject *exc = NULL;
7725 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007726 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007727 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007728 PyObject *rep;
7729 int ret = -1;
7730
7731 assert(insize > 0);
7732
7733 encoding = code_page_name(code_page, &encoding_obj);
7734 if (encoding == NULL)
7735 return -1;
7736
7737 if (errors == NULL || strcmp(errors, "strict") == 0) {
7738 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7739 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007740 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007741 if (exc != NULL) {
7742 PyCodec_StrictErrors(exc);
7743 Py_DECREF(exc);
7744 }
7745 Py_XDECREF(encoding_obj);
7746 return -1;
7747 }
7748
7749 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7750 pusedDefaultChar = &usedDefaultChar;
7751 else
7752 pusedDefaultChar = NULL;
7753
7754 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7755 PyErr_NoMemory();
7756 goto error;
7757 }
7758 outsize = insize * Py_ARRAY_LENGTH(buffer);
7759
7760 if (*outbytes == NULL) {
7761 /* Create string object */
7762 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7763 if (*outbytes == NULL)
7764 goto error;
7765 out = PyBytes_AS_STRING(*outbytes);
7766 }
7767 else {
7768 /* Extend string object */
7769 Py_ssize_t n = PyBytes_Size(*outbytes);
7770 if (n > PY_SSIZE_T_MAX - outsize) {
7771 PyErr_NoMemory();
7772 goto error;
7773 }
7774 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7775 goto error;
7776 out = PyBytes_AS_STRING(*outbytes) + n;
7777 }
7778
7779 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007780 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007781 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007782 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7783 wchar_t chars[2];
7784 int charsize;
7785 if (ch < 0x10000) {
7786 chars[0] = (wchar_t)ch;
7787 charsize = 1;
7788 }
7789 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007790 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7791 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007792 charsize = 2;
7793 }
7794
Victor Stinner3a50e702011-10-18 21:21:00 +02007795 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007796 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007797 buffer, Py_ARRAY_LENGTH(buffer),
7798 NULL, pusedDefaultChar);
7799 if (outsize > 0) {
7800 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7801 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007802 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007803 memcpy(out, buffer, outsize);
7804 out += outsize;
7805 continue;
7806 }
7807 }
7808 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7809 PyErr_SetFromWindowsErr(0);
7810 goto error;
7811 }
7812
Victor Stinner3a50e702011-10-18 21:21:00 +02007813 rep = unicode_encode_call_errorhandler(
7814 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007815 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007816 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007817 if (rep == NULL)
7818 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007819 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007820
7821 if (PyBytes_Check(rep)) {
7822 outsize = PyBytes_GET_SIZE(rep);
7823 if (outsize != 1) {
7824 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7825 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7826 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7827 Py_DECREF(rep);
7828 goto error;
7829 }
7830 out = PyBytes_AS_STRING(*outbytes) + offset;
7831 }
7832 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7833 out += outsize;
7834 }
7835 else {
7836 Py_ssize_t i;
7837 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03007838 const void *data;
Victor Stinner3a50e702011-10-18 21:21:00 +02007839
Benjamin Petersonbac79492012-01-14 13:34:47 -05007840 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007841 Py_DECREF(rep);
7842 goto error;
7843 }
7844
7845 outsize = PyUnicode_GET_LENGTH(rep);
7846 if (outsize != 1) {
7847 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7848 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7849 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7850 Py_DECREF(rep);
7851 goto error;
7852 }
7853 out = PyBytes_AS_STRING(*outbytes) + offset;
7854 }
7855 kind = PyUnicode_KIND(rep);
7856 data = PyUnicode_DATA(rep);
7857 for (i=0; i < outsize; i++) {
7858 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7859 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007860 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007861 encoding, unicode,
7862 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007863 "unable to encode error handler result to ASCII");
7864 Py_DECREF(rep);
7865 goto error;
7866 }
7867 *out = (unsigned char)ch;
7868 out++;
7869 }
7870 }
7871 Py_DECREF(rep);
7872 }
7873 /* write a NUL byte */
7874 *out = 0;
7875 outsize = out - PyBytes_AS_STRING(*outbytes);
7876 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7877 if (_PyBytes_Resize(outbytes, outsize) < 0)
7878 goto error;
7879 ret = 0;
7880
7881error:
7882 Py_XDECREF(encoding_obj);
7883 Py_XDECREF(errorHandler);
7884 Py_XDECREF(exc);
7885 return ret;
7886}
7887
Victor Stinner3a50e702011-10-18 21:21:00 +02007888static PyObject *
7889encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007890 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007891 const char *errors)
7892{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007893 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007894 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007895 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007896 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007897
Victor Stinner29dacf22015-01-26 16:41:32 +01007898 if (!PyUnicode_Check(unicode)) {
7899 PyErr_BadArgument();
7900 return NULL;
7901 }
7902
Benjamin Petersonbac79492012-01-14 13:34:47 -05007903 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007904 return NULL;
7905 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007906
Victor Stinner3a50e702011-10-18 21:21:00 +02007907 if (code_page < 0) {
7908 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7909 return NULL;
7910 }
7911
Martin v. Löwis3d325192011-11-04 18:23:06 +01007912 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007913 return PyBytes_FromStringAndSize(NULL, 0);
7914
Victor Stinner7581cef2011-11-03 22:32:33 +01007915 offset = 0;
7916 do
7917 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007918#ifdef NEED_RETRY
Steve Dower7ebdda02019-08-21 16:22:33 -07007919 if (len > DECODING_CHUNK_SIZE) {
7920 chunk_len = DECODING_CHUNK_SIZE;
Victor Stinner76a31a62011-11-04 00:05:13 +01007921 done = 0;
7922 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007923 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007924#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007925 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007926 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007927 done = 1;
7928 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007929
Victor Stinner76a31a62011-11-04 00:05:13 +01007930 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007931 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007932 errors);
7933 if (ret == -2)
7934 ret = encode_code_page_errors(code_page, &outbytes,
7935 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007936 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007937 if (ret < 0) {
7938 Py_XDECREF(outbytes);
7939 return NULL;
7940 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007941
Victor Stinner7581cef2011-11-03 22:32:33 +01007942 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007943 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007944 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007945
Victor Stinner3a50e702011-10-18 21:21:00 +02007946 return outbytes;
7947}
7948
7949PyObject *
7950PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7951 Py_ssize_t size,
7952 const char *errors)
7953{
Victor Stinner7581cef2011-11-03 22:32:33 +01007954 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007955 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007956 if (unicode == NULL)
7957 return NULL;
7958 res = encode_code_page(CP_ACP, unicode, errors);
7959 Py_DECREF(unicode);
7960 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007961}
7962
7963PyObject *
7964PyUnicode_EncodeCodePage(int code_page,
7965 PyObject *unicode,
7966 const char *errors)
7967{
Victor Stinner7581cef2011-11-03 22:32:33 +01007968 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007969}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007970
Alexander Belopolsky40018472011-02-26 01:02:56 +00007971PyObject *
7972PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007973{
Victor Stinner7581cef2011-11-03 22:32:33 +01007974 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007975}
7976
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007977#undef NEED_RETRY
7978
Steve Dowercc16be82016-09-08 10:35:16 -07007979#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007980
Guido van Rossumd57fd912000-03-10 22:53:23 +00007981/* --- Character Mapping Codec -------------------------------------------- */
7982
Victor Stinnerfb161b12013-04-18 01:44:27 +02007983static int
7984charmap_decode_string(const char *s,
7985 Py_ssize_t size,
7986 PyObject *mapping,
7987 const char *errors,
7988 _PyUnicodeWriter *writer)
7989{
7990 const char *starts = s;
7991 const char *e;
7992 Py_ssize_t startinpos, endinpos;
7993 PyObject *errorHandler = NULL, *exc = NULL;
7994 Py_ssize_t maplen;
7995 enum PyUnicode_Kind mapkind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03007996 const void *mapdata;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007997 Py_UCS4 x;
7998 unsigned char ch;
7999
8000 if (PyUnicode_READY(mapping) == -1)
8001 return -1;
8002
8003 maplen = PyUnicode_GET_LENGTH(mapping);
8004 mapdata = PyUnicode_DATA(mapping);
8005 mapkind = PyUnicode_KIND(mapping);
8006
8007 e = s + size;
8008
8009 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
8010 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
8011 * is disabled in encoding aliases, latin1 is preferred because
8012 * its implementation is faster. */
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03008013 const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
Victor Stinnerfb161b12013-04-18 01:44:27 +02008014 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8015 Py_UCS4 maxchar = writer->maxchar;
8016
8017 assert (writer->kind == PyUnicode_1BYTE_KIND);
8018 while (s < e) {
8019 ch = *s;
8020 x = mapdata_ucs1[ch];
8021 if (x > maxchar) {
8022 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
8023 goto onError;
8024 maxchar = writer->maxchar;
8025 outdata = (Py_UCS1 *)writer->data;
8026 }
8027 outdata[writer->pos] = x;
8028 writer->pos++;
8029 ++s;
8030 }
8031 return 0;
8032 }
8033
8034 while (s < e) {
8035 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
8036 enum PyUnicode_Kind outkind = writer->kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03008037 const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
Victor Stinnerfb161b12013-04-18 01:44:27 +02008038 if (outkind == PyUnicode_1BYTE_KIND) {
8039 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
8040 Py_UCS4 maxchar = writer->maxchar;
8041 while (s < e) {
8042 ch = *s;
8043 x = mapdata_ucs2[ch];
8044 if (x > maxchar)
8045 goto Error;
8046 outdata[writer->pos] = x;
8047 writer->pos++;
8048 ++s;
8049 }
8050 break;
8051 }
8052 else if (outkind == PyUnicode_2BYTE_KIND) {
8053 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
8054 while (s < e) {
8055 ch = *s;
8056 x = mapdata_ucs2[ch];
8057 if (x == 0xFFFE)
8058 goto Error;
8059 outdata[writer->pos] = x;
8060 writer->pos++;
8061 ++s;
8062 }
8063 break;
8064 }
8065 }
8066 ch = *s;
8067
8068 if (ch < maplen)
8069 x = PyUnicode_READ(mapkind, mapdata, ch);
8070 else
8071 x = 0xfffe; /* invalid value */
8072Error:
8073 if (x == 0xfffe)
8074 {
8075 /* undefined mapping */
8076 startinpos = s-starts;
8077 endinpos = startinpos+1;
8078 if (unicode_decode_call_errorhandler_writer(
8079 errors, &errorHandler,
8080 "charmap", "character maps to <undefined>",
8081 &starts, &e, &startinpos, &endinpos, &exc, &s,
8082 writer)) {
8083 goto onError;
8084 }
8085 continue;
8086 }
8087
8088 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
8089 goto onError;
8090 ++s;
8091 }
8092 Py_XDECREF(errorHandler);
8093 Py_XDECREF(exc);
8094 return 0;
8095
8096onError:
8097 Py_XDECREF(errorHandler);
8098 Py_XDECREF(exc);
8099 return -1;
8100}
8101
8102static int
8103charmap_decode_mapping(const char *s,
8104 Py_ssize_t size,
8105 PyObject *mapping,
8106 const char *errors,
8107 _PyUnicodeWriter *writer)
8108{
8109 const char *starts = s;
8110 const char *e;
8111 Py_ssize_t startinpos, endinpos;
8112 PyObject *errorHandler = NULL, *exc = NULL;
8113 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02008114 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02008115
8116 e = s + size;
8117
8118 while (s < e) {
8119 ch = *s;
8120
8121 /* Get mapping (char ordinal -> integer, Unicode char or None) */
8122 key = PyLong_FromLong((long)ch);
8123 if (key == NULL)
8124 goto onError;
8125
8126 item = PyObject_GetItem(mapping, key);
8127 Py_DECREF(key);
8128 if (item == NULL) {
8129 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8130 /* No mapping found means: mapping is undefined. */
8131 PyErr_Clear();
8132 goto Undefined;
8133 } else
8134 goto onError;
8135 }
8136
8137 /* Apply mapping */
8138 if (item == Py_None)
8139 goto Undefined;
8140 if (PyLong_Check(item)) {
8141 long value = PyLong_AS_LONG(item);
8142 if (value == 0xFFFE)
8143 goto Undefined;
8144 if (value < 0 || value > MAX_UNICODE) {
8145 PyErr_Format(PyExc_TypeError,
8146 "character mapping must be in range(0x%lx)",
8147 (unsigned long)MAX_UNICODE + 1);
8148 goto onError;
8149 }
8150
8151 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8152 goto onError;
8153 }
8154 else if (PyUnicode_Check(item)) {
8155 if (PyUnicode_READY(item) == -1)
8156 goto onError;
8157 if (PyUnicode_GET_LENGTH(item) == 1) {
8158 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8159 if (value == 0xFFFE)
8160 goto Undefined;
8161 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8162 goto onError;
8163 }
8164 else {
8165 writer->overallocate = 1;
8166 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8167 goto onError;
8168 }
8169 }
8170 else {
8171 /* wrong return value */
8172 PyErr_SetString(PyExc_TypeError,
8173 "character mapping must return integer, None or str");
8174 goto onError;
8175 }
8176 Py_CLEAR(item);
8177 ++s;
8178 continue;
8179
8180Undefined:
8181 /* undefined mapping */
8182 Py_CLEAR(item);
8183 startinpos = s-starts;
8184 endinpos = startinpos+1;
8185 if (unicode_decode_call_errorhandler_writer(
8186 errors, &errorHandler,
8187 "charmap", "character maps to <undefined>",
8188 &starts, &e, &startinpos, &endinpos, &exc, &s,
8189 writer)) {
8190 goto onError;
8191 }
8192 }
8193 Py_XDECREF(errorHandler);
8194 Py_XDECREF(exc);
8195 return 0;
8196
8197onError:
8198 Py_XDECREF(item);
8199 Py_XDECREF(errorHandler);
8200 Py_XDECREF(exc);
8201 return -1;
8202}
8203
Alexander Belopolsky40018472011-02-26 01:02:56 +00008204PyObject *
8205PyUnicode_DecodeCharmap(const char *s,
8206 Py_ssize_t size,
8207 PyObject *mapping,
8208 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008209{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008210 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008211
Guido van Rossumd57fd912000-03-10 22:53:23 +00008212 /* Default to Latin-1 */
8213 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008214 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008215
Guido van Rossumd57fd912000-03-10 22:53:23 +00008216 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008217 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008218 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008219 writer.min_length = size;
8220 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008221 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008222
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008223 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008224 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8225 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008226 }
8227 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008228 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8229 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008230 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008231 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008232
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008234 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008235 return NULL;
8236}
8237
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008238/* Charmap encoding: the lookup table */
8239
Alexander Belopolsky40018472011-02-26 01:02:56 +00008240struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 PyObject_HEAD
8242 unsigned char level1[32];
8243 int count2, count3;
8244 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008245};
8246
8247static PyObject*
8248encoding_map_size(PyObject *obj, PyObject* args)
8249{
8250 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008251 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008253}
8254
8255static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008256 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 PyDoc_STR("Return the size (in bytes) of this object") },
8258 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008259};
8260
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008261static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008262 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 "EncodingMap", /*tp_name*/
8264 sizeof(struct encoding_map), /*tp_basicsize*/
8265 0, /*tp_itemsize*/
8266 /* methods */
Inada Naoki7d408692019-05-29 17:23:27 +09008267 0, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02008268 0, /*tp_vectorcall_offset*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 0, /*tp_getattr*/
8270 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02008271 0, /*tp_as_async*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008272 0, /*tp_repr*/
8273 0, /*tp_as_number*/
8274 0, /*tp_as_sequence*/
8275 0, /*tp_as_mapping*/
8276 0, /*tp_hash*/
8277 0, /*tp_call*/
8278 0, /*tp_str*/
8279 0, /*tp_getattro*/
8280 0, /*tp_setattro*/
8281 0, /*tp_as_buffer*/
8282 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8283 0, /*tp_doc*/
8284 0, /*tp_traverse*/
8285 0, /*tp_clear*/
8286 0, /*tp_richcompare*/
8287 0, /*tp_weaklistoffset*/
8288 0, /*tp_iter*/
8289 0, /*tp_iternext*/
8290 encoding_map_methods, /*tp_methods*/
8291 0, /*tp_members*/
8292 0, /*tp_getset*/
8293 0, /*tp_base*/
8294 0, /*tp_dict*/
8295 0, /*tp_descr_get*/
8296 0, /*tp_descr_set*/
8297 0, /*tp_dictoffset*/
8298 0, /*tp_init*/
8299 0, /*tp_alloc*/
8300 0, /*tp_new*/
8301 0, /*tp_free*/
8302 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008303};
8304
8305PyObject*
8306PyUnicode_BuildEncodingMap(PyObject* string)
8307{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008308 PyObject *result;
8309 struct encoding_map *mresult;
8310 int i;
8311 int need_dict = 0;
8312 unsigned char level1[32];
8313 unsigned char level2[512];
8314 unsigned char *mlevel1, *mlevel2, *mlevel3;
8315 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008316 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03008317 const void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008318 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008319 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008320
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008321 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008322 PyErr_BadArgument();
8323 return NULL;
8324 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008325 kind = PyUnicode_KIND(string);
8326 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008327 length = PyUnicode_GET_LENGTH(string);
8328 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008329 memset(level1, 0xFF, sizeof level1);
8330 memset(level2, 0xFF, sizeof level2);
8331
8332 /* If there isn't a one-to-one mapping of NULL to \0,
8333 or if there are non-BMP characters, we need to use
8334 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008335 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008336 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008337 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008338 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008339 ch = PyUnicode_READ(kind, data, i);
8340 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008341 need_dict = 1;
8342 break;
8343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008344 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008345 /* unmapped character */
8346 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008347 l1 = ch >> 11;
8348 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008349 if (level1[l1] == 0xFF)
8350 level1[l1] = count2++;
8351 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008352 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008353 }
8354
8355 if (count2 >= 0xFF || count3 >= 0xFF)
8356 need_dict = 1;
8357
8358 if (need_dict) {
8359 PyObject *result = PyDict_New();
8360 PyObject *key, *value;
8361 if (!result)
8362 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008363 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008364 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008365 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008366 if (!key || !value)
8367 goto failed1;
8368 if (PyDict_SetItem(result, key, value) == -1)
8369 goto failed1;
8370 Py_DECREF(key);
8371 Py_DECREF(value);
8372 }
8373 return result;
8374 failed1:
8375 Py_XDECREF(key);
8376 Py_XDECREF(value);
8377 Py_DECREF(result);
8378 return NULL;
8379 }
8380
8381 /* Create a three-level trie */
8382 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8383 16*count2 + 128*count3 - 1);
8384 if (!result)
8385 return PyErr_NoMemory();
8386 PyObject_Init(result, &EncodingMapType);
8387 mresult = (struct encoding_map*)result;
8388 mresult->count2 = count2;
8389 mresult->count3 = count3;
8390 mlevel1 = mresult->level1;
8391 mlevel2 = mresult->level23;
8392 mlevel3 = mresult->level23 + 16*count2;
8393 memcpy(mlevel1, level1, 32);
8394 memset(mlevel2, 0xFF, 16*count2);
8395 memset(mlevel3, 0, 128*count3);
8396 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008397 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008398 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008399 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8400 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008401 /* unmapped character */
8402 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008403 o1 = ch>>11;
8404 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008405 i2 = 16*mlevel1[o1] + o2;
8406 if (mlevel2[i2] == 0xFF)
8407 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008408 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008409 i3 = 128*mlevel2[i2] + o3;
8410 mlevel3[i3] = i;
8411 }
8412 return result;
8413}
8414
8415static int
Victor Stinner22168992011-11-20 17:09:18 +01008416encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008417{
8418 struct encoding_map *map = (struct encoding_map*)mapping;
8419 int l1 = c>>11;
8420 int l2 = (c>>7) & 0xF;
8421 int l3 = c & 0x7F;
8422 int i;
8423
Victor Stinner22168992011-11-20 17:09:18 +01008424 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008425 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008426 if (c == 0)
8427 return 0;
8428 /* level 1*/
8429 i = map->level1[l1];
8430 if (i == 0xFF) {
8431 return -1;
8432 }
8433 /* level 2*/
8434 i = map->level23[16*i+l2];
8435 if (i == 0xFF) {
8436 return -1;
8437 }
8438 /* level 3 */
8439 i = map->level23[16*map->count2 + 128*i + l3];
8440 if (i == 0) {
8441 return -1;
8442 }
8443 return i;
8444}
8445
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446/* Lookup the character ch in the mapping. If the character
8447 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008448 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008449static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008450charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008451{
Christian Heimes217cfd12007-12-02 14:31:20 +00008452 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008453 PyObject *x;
8454
8455 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457 x = PyObject_GetItem(mapping, w);
8458 Py_DECREF(w);
8459 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8461 /* No mapping found means: mapping is undefined. */
8462 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008463 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 } else
8465 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008466 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008467 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008469 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 long value = PyLong_AS_LONG(x);
8471 if (value < 0 || value > 255) {
8472 PyErr_SetString(PyExc_TypeError,
8473 "character mapping must be in range(256)");
8474 Py_DECREF(x);
8475 return NULL;
8476 }
8477 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008478 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008479 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008481 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008482 /* wrong return value */
8483 PyErr_Format(PyExc_TypeError,
8484 "character mapping must return integer, bytes or None, not %.400s",
Victor Stinner58ac7002020-02-07 03:04:21 +01008485 Py_TYPE(x)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 Py_DECREF(x);
8487 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008488 }
8489}
8490
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008491static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008492charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008493{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008494 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8495 /* exponentially overallocate to minimize reallocations */
8496 if (requiredsize < 2*outsize)
8497 requiredsize = 2*outsize;
8498 if (_PyBytes_Resize(outobj, requiredsize))
8499 return -1;
8500 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008501}
8502
Benjamin Peterson14339b62009-01-31 16:36:08 +00008503typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008505} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008507 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508 space is available. Return a new reference to the object that
8509 was put in the output buffer, or Py_None, if the mapping was undefined
8510 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008511 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008512static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008513charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008514 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008516 PyObject *rep;
8517 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008518 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008519
Andy Lesterdffe4c02020-03-04 07:15:20 -06008520 if (Py_IS_TYPE(mapping, &EncodingMapType)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008521 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008523 if (res == -1)
8524 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 if (outsize<requiredsize)
8526 if (charmapencode_resize(outobj, outpos, requiredsize))
8527 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008528 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 outstart[(*outpos)++] = (char)res;
8530 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008531 }
8532
8533 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008534 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008536 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 Py_DECREF(rep);
8538 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008539 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 if (PyLong_Check(rep)) {
8541 Py_ssize_t requiredsize = *outpos+1;
8542 if (outsize<requiredsize)
8543 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8544 Py_DECREF(rep);
8545 return enc_EXCEPTION;
8546 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008547 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008549 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 else {
8551 const char *repchars = PyBytes_AS_STRING(rep);
8552 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8553 Py_ssize_t requiredsize = *outpos+repsize;
8554 if (outsize<requiredsize)
8555 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8556 Py_DECREF(rep);
8557 return enc_EXCEPTION;
8558 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008559 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 memcpy(outstart + *outpos, repchars, repsize);
8561 *outpos += repsize;
8562 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008564 Py_DECREF(rep);
8565 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008566}
8567
8568/* handle an error in PyUnicode_EncodeCharmap
8569 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008570static int
8571charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008572 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008573 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008574 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008575 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576{
8577 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008578 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008579 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008580 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03008581 const void *data;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008582 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008583 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008584 Py_ssize_t collstartpos = *inpos;
8585 Py_ssize_t collendpos = *inpos+1;
8586 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008587 const char *encoding = "charmap";
8588 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008589 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008590 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008591 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008592
Benjamin Petersonbac79492012-01-14 13:34:47 -05008593 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008594 return -1;
8595 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 /* find all unencodable characters */
8597 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008598 PyObject *rep;
Andy Lesterdffe4c02020-03-04 07:15:20 -06008599 if (Py_IS_TYPE(mapping, &EncodingMapType)) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008600 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008601 val = encoding_map_lookup(ch, mapping);
8602 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008603 break;
8604 ++collendpos;
8605 continue;
8606 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008607
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008608 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8609 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 if (rep==NULL)
8611 return -1;
8612 else if (rep!=Py_None) {
8613 Py_DECREF(rep);
8614 break;
8615 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008616 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 }
8619 /* cache callback name lookup
8620 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008621 if (*error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02008622 *error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02008623
8624 switch (*error_handler) {
8625 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008626 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008627 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008628
8629 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008630 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 x = charmapencode_output('?', mapping, res, respos);
8632 if (x==enc_EXCEPTION) {
8633 return -1;
8634 }
8635 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008636 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 return -1;
8638 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008639 }
8640 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008641 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008642 *inpos = collendpos;
8643 break;
Victor Stinner50149202015-09-22 00:26:54 +02008644
8645 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008646 /* generate replacement (temporarily (mis)uses p) */
8647 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 char buffer[2+29+1+1];
8649 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008650 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 for (cp = buffer; *cp; ++cp) {
8652 x = charmapencode_output(*cp, mapping, res, respos);
8653 if (x==enc_EXCEPTION)
8654 return -1;
8655 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008656 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 return -1;
8658 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008659 }
8660 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008661 *inpos = collendpos;
8662 break;
Victor Stinner50149202015-09-22 00:26:54 +02008663
Benjamin Peterson14339b62009-01-31 16:36:08 +00008664 default:
Victor Stinner50149202015-09-22 00:26:54 +02008665 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008666 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008667 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008668 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008670 if (PyBytes_Check(repunicode)) {
8671 /* Directly copy bytes result to output. */
8672 Py_ssize_t outsize = PyBytes_Size(*res);
8673 Py_ssize_t requiredsize;
8674 repsize = PyBytes_Size(repunicode);
8675 requiredsize = *respos + repsize;
8676 if (requiredsize > outsize)
8677 /* Make room for all additional bytes. */
8678 if (charmapencode_resize(res, respos, requiredsize)) {
8679 Py_DECREF(repunicode);
8680 return -1;
8681 }
8682 memcpy(PyBytes_AsString(*res) + *respos,
8683 PyBytes_AsString(repunicode), repsize);
8684 *respos += repsize;
8685 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008686 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008687 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008688 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008689 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008690 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008691 Py_DECREF(repunicode);
8692 return -1;
8693 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008694 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008695 data = PyUnicode_DATA(repunicode);
8696 kind = PyUnicode_KIND(repunicode);
8697 for (index = 0; index < repsize; index++) {
8698 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8699 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008700 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008701 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 return -1;
8703 }
8704 else if (x==enc_FAILED) {
8705 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008706 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 return -1;
8708 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008709 }
8710 *inpos = newpos;
8711 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008712 }
8713 return 0;
8714}
8715
Alexander Belopolsky40018472011-02-26 01:02:56 +00008716PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008717_PyUnicode_EncodeCharmap(PyObject *unicode,
8718 PyObject *mapping,
8719 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008720{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008721 /* output object */
8722 PyObject *res = NULL;
8723 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008724 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008725 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008726 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008727 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008728 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008729 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008730 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03008731 const void *data;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008732 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008733
Benjamin Petersonbac79492012-01-14 13:34:47 -05008734 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008735 return NULL;
8736 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008737 data = PyUnicode_DATA(unicode);
8738 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008739
Guido van Rossumd57fd912000-03-10 22:53:23 +00008740 /* Default to Latin-1 */
8741 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008742 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008743
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008744 /* allocate enough for a simple encoding without
8745 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008746 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008747 if (res == NULL)
8748 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008749 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008751
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008752 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008753 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008755 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008756 if (x==enc_EXCEPTION) /* error */
8757 goto onError;
8758 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008759 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008760 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008761 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 &res, &respos)) {
8763 goto onError;
8764 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008765 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008766 else
8767 /* done with this character => adjust input position */
8768 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008769 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008770
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008771 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008772 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008773 if (_PyBytes_Resize(&res, respos) < 0)
8774 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008775
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008776 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008777 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008778 return res;
8779
Benjamin Peterson29060642009-01-31 22:14:21 +00008780 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008781 Py_XDECREF(res);
8782 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008783 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784 return NULL;
8785}
8786
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008787/* Deprecated */
8788PyObject *
8789PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8790 Py_ssize_t size,
8791 PyObject *mapping,
8792 const char *errors)
8793{
8794 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008795 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008796 if (unicode == NULL)
8797 return NULL;
8798 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8799 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008800 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008801}
8802
Alexander Belopolsky40018472011-02-26 01:02:56 +00008803PyObject *
8804PyUnicode_AsCharmapString(PyObject *unicode,
8805 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008806{
8807 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008808 PyErr_BadArgument();
8809 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008810 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008811 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008812}
8813
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008814/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008815static void
8816make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008818 Py_ssize_t startpos, Py_ssize_t endpos,
8819 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008820{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008821 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008822 *exceptionObject = _PyUnicodeTranslateError_Create(
8823 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008824 }
8825 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008826 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8827 goto onError;
8828 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8829 goto onError;
8830 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8831 goto onError;
8832 return;
8833 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008834 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008835 }
8836}
8837
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008838/* error handling callback helper:
8839 build arguments, call the callback and check the arguments,
8840 put the result into newpos and return the replacement string, which
8841 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008842static PyObject *
8843unicode_translate_call_errorhandler(const char *errors,
8844 PyObject **errorHandler,
8845 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008846 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008847 Py_ssize_t startpos, Py_ssize_t endpos,
8848 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008849{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008850 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008851
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008852 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008853 PyObject *restuple;
8854 PyObject *resunicode;
8855
8856 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008857 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008858 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008859 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008860 }
8861
8862 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008863 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008864 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008865 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008866
Petr Viktorinffd97532020-02-11 17:46:57 +01008867 restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008868 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008869 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008870 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008871 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008872 Py_DECREF(restuple);
8873 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008874 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008875 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008876 &resunicode, &i_newpos)) {
8877 Py_DECREF(restuple);
8878 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008879 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008880 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008882 else
8883 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008885 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008886 Py_DECREF(restuple);
8887 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008888 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008889 Py_INCREF(resunicode);
8890 Py_DECREF(restuple);
8891 return resunicode;
8892}
8893
8894/* Lookup the character ch in the mapping and put the result in result,
8895 which must be decrefed by the caller.
8896 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008897static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008898charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008899{
Christian Heimes217cfd12007-12-02 14:31:20 +00008900 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008901 PyObject *x;
8902
8903 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008904 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008905 x = PyObject_GetItem(mapping, w);
8906 Py_DECREF(w);
8907 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008908 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8909 /* No mapping found means: use 1:1 mapping. */
8910 PyErr_Clear();
8911 *result = NULL;
8912 return 0;
8913 } else
8914 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008915 }
8916 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 *result = x;
8918 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008919 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008920 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008921 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008922 if (value < 0 || value > MAX_UNICODE) {
8923 PyErr_Format(PyExc_ValueError,
8924 "character mapping must be in range(0x%x)",
8925 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008926 Py_DECREF(x);
8927 return -1;
8928 }
8929 *result = x;
8930 return 0;
8931 }
8932 else if (PyUnicode_Check(x)) {
8933 *result = x;
8934 return 0;
8935 }
8936 else {
8937 /* wrong return value */
8938 PyErr_SetString(PyExc_TypeError,
8939 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008940 Py_DECREF(x);
8941 return -1;
8942 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008943}
Victor Stinner1194ea02014-04-04 19:37:40 +02008944
8945/* lookup the character, write the result into the writer.
8946 Return 1 if the result was written into the writer, return 0 if the mapping
8947 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008948static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008949charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8950 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008951{
Victor Stinner1194ea02014-04-04 19:37:40 +02008952 PyObject *item;
8953
8954 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008955 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008956
8957 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008958 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008959 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008960 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008961 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008962 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008963 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008964
8965 if (item == Py_None) {
8966 Py_DECREF(item);
8967 return 0;
8968 }
8969
8970 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008971 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8972 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8973 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008974 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8975 Py_DECREF(item);
8976 return -1;
8977 }
8978 Py_DECREF(item);
8979 return 1;
8980 }
8981
8982 if (!PyUnicode_Check(item)) {
8983 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008984 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008985 }
8986
8987 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8988 Py_DECREF(item);
8989 return -1;
8990 }
8991
8992 Py_DECREF(item);
8993 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008994}
8995
Victor Stinner89a76ab2014-04-05 11:44:04 +02008996static int
8997unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8998 Py_UCS1 *translate)
8999{
Benjamin Peterson1365de72014-04-07 20:15:41 -04009000 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009001 int ret = 0;
9002
Victor Stinner89a76ab2014-04-05 11:44:04 +02009003 if (charmaptranslate_lookup(ch, mapping, &item)) {
9004 return -1;
9005 }
9006
9007 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04009008 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02009009 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009010 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04009011 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02009012 /* not found => default to 1:1 mapping */
9013 translate[ch] = ch;
9014 return 1;
9015 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04009016 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02009017 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02009018 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
9019 used it */
9020 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02009021 /* invalid character or character outside ASCII:
9022 skip the fast translate */
9023 goto exit;
9024 }
9025 translate[ch] = (Py_UCS1)replace;
9026 }
9027 else if (PyUnicode_Check(item)) {
9028 Py_UCS4 replace;
9029
9030 if (PyUnicode_READY(item) == -1) {
9031 Py_DECREF(item);
9032 return -1;
9033 }
9034 if (PyUnicode_GET_LENGTH(item) != 1)
9035 goto exit;
9036
9037 replace = PyUnicode_READ_CHAR(item, 0);
9038 if (replace > 127)
9039 goto exit;
9040 translate[ch] = (Py_UCS1)replace;
9041 }
9042 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04009043 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02009044 goto exit;
9045 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009046 ret = 1;
9047
Benjamin Peterson1365de72014-04-07 20:15:41 -04009048 exit:
9049 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009050 return ret;
9051}
9052
9053/* Fast path for ascii => ascii translation. Return 1 if the whole string
9054 was translated into writer, return 0 if the input string was partially
9055 translated into writer, raise an exception and return -1 on error. */
9056static int
9057unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01009058 _PyUnicodeWriter *writer, int ignore,
9059 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009060{
Victor Stinner872b2912014-04-05 14:27:07 +02009061 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009062 Py_ssize_t len;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009063 const Py_UCS1 *in, *end;
9064 Py_UCS1 *out;
Victor Stinner872b2912014-04-05 14:27:07 +02009065 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009066
Victor Stinner89a76ab2014-04-05 11:44:04 +02009067 len = PyUnicode_GET_LENGTH(input);
9068
Victor Stinner872b2912014-04-05 14:27:07 +02009069 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009070
9071 in = PyUnicode_1BYTE_DATA(input);
9072 end = in + len;
9073
9074 assert(PyUnicode_IS_ASCII(writer->buffer));
9075 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
9076 out = PyUnicode_1BYTE_DATA(writer->buffer);
9077
Victor Stinner872b2912014-04-05 14:27:07 +02009078 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02009079 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02009080 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02009081 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02009082 int translate = unicode_fast_translate_lookup(mapping, ch,
9083 ascii_table);
9084 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009085 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02009086 if (translate == 0)
9087 goto exit;
9088 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02009089 }
Victor Stinner872b2912014-04-05 14:27:07 +02009090 if (ch2 == 0xfe) {
9091 if (ignore)
9092 continue;
9093 goto exit;
9094 }
9095 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009096 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02009097 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009098 }
Victor Stinner872b2912014-04-05 14:27:07 +02009099 res = 1;
9100
9101exit:
9102 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01009103 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02009104 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009105}
9106
Victor Stinner3222da22015-10-01 22:07:32 +02009107static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108_PyUnicode_TranslateCharmap(PyObject *input,
9109 PyObject *mapping,
9110 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009111{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 /* input object */
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009113 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009114 Py_ssize_t size, i;
9115 int kind;
9116 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02009117 _PyUnicodeWriter writer;
9118 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02009119 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009120 PyObject *errorHandler = NULL;
9121 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02009122 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02009123 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009124
Guido van Rossumd57fd912000-03-10 22:53:23 +00009125 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009126 PyErr_BadArgument();
9127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009128 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009130 if (PyUnicode_READY(input) == -1)
9131 return NULL;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009132 data = PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133 kind = PyUnicode_KIND(input);
9134 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009135
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009136 if (size == 0)
9137 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009138
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009139 /* allocate enough for a simple 1:1 translation without
9140 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02009141 _PyUnicodeWriter_Init(&writer);
9142 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009143 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009144
Victor Stinner872b2912014-04-05 14:27:07 +02009145 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
9146
Victor Stinner33798672016-03-01 21:59:58 +01009147 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02009148 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01009149 if (PyUnicode_IS_ASCII(input)) {
9150 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9151 if (res < 0) {
9152 _PyUnicodeWriter_Dealloc(&writer);
9153 return NULL;
9154 }
9155 if (res == 1)
9156 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009157 }
Victor Stinner33798672016-03-01 21:59:58 +01009158 else {
9159 i = 0;
9160 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009161
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009162 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009163 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009164 int translate;
9165 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9166 Py_ssize_t newpos;
9167 /* startpos for collecting untranslatable chars */
9168 Py_ssize_t collstart;
9169 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009170 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009171
Victor Stinner1194ea02014-04-04 19:37:40 +02009172 ch = PyUnicode_READ(kind, data, i);
9173 translate = charmaptranslate_output(ch, mapping, &writer);
9174 if (translate < 0)
9175 goto onError;
9176
9177 if (translate != 0) {
9178 /* it worked => adjust input pointer */
9179 ++i;
9180 continue;
9181 }
9182
9183 /* untranslatable character */
9184 collstart = i;
9185 collend = i+1;
9186
9187 /* find all untranslatable characters */
9188 while (collend < size) {
9189 PyObject *x;
9190 ch = PyUnicode_READ(kind, data, collend);
9191 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009192 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009193 Py_XDECREF(x);
9194 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009195 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009196 ++collend;
9197 }
9198
9199 if (ignore) {
9200 i = collend;
9201 }
9202 else {
9203 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9204 reason, input, &exc,
9205 collstart, collend, &newpos);
9206 if (repunicode == NULL)
9207 goto onError;
9208 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009209 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009210 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009211 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009212 Py_DECREF(repunicode);
9213 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009214 }
9215 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009216 Py_XDECREF(exc);
9217 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009218 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009219
Benjamin Peterson29060642009-01-31 22:14:21 +00009220 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009221 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009222 Py_XDECREF(exc);
9223 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009224 return NULL;
9225}
9226
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009227/* Deprecated. Use PyUnicode_Translate instead. */
9228PyObject *
9229PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9230 Py_ssize_t size,
9231 PyObject *mapping,
9232 const char *errors)
9233{
Christian Heimes5f520f42012-09-11 14:03:25 +02009234 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009235 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009236 if (!unicode)
9237 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009238 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9239 Py_DECREF(unicode);
9240 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009241}
9242
Alexander Belopolsky40018472011-02-26 01:02:56 +00009243PyObject *
9244PyUnicode_Translate(PyObject *str,
9245 PyObject *mapping,
9246 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009247{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009248 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009249 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009250 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009251}
Tim Petersced69f82003-09-16 20:30:58 +00009252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009253PyObject *
9254_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9255{
9256 if (!PyUnicode_Check(unicode)) {
9257 PyErr_BadInternalCall();
9258 return NULL;
9259 }
9260 if (PyUnicode_READY(unicode) == -1)
9261 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009262 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263 /* If the string is already ASCII, just return the same string */
9264 Py_INCREF(unicode);
9265 return unicode;
9266 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009267
9268 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9269 PyObject *result = PyUnicode_New(len, 127);
9270 if (result == NULL) {
9271 return NULL;
9272 }
9273
9274 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9275 int kind = PyUnicode_KIND(unicode);
9276 const void *data = PyUnicode_DATA(unicode);
9277 Py_ssize_t i;
9278 for (i = 0; i < len; ++i) {
9279 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9280 if (ch < 127) {
9281 out[i] = ch;
9282 }
9283 else if (Py_UNICODE_ISSPACE(ch)) {
9284 out[i] = ' ';
9285 }
9286 else {
9287 int decimal = Py_UNICODE_TODECIMAL(ch);
9288 if (decimal < 0) {
9289 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009290 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009291 _PyUnicode_LENGTH(result) = i + 1;
9292 break;
9293 }
9294 out[i] = '0' + decimal;
9295 }
9296 }
9297
INADA Naoki16dfca42018-07-14 12:06:43 +09009298 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009299 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009300}
9301
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009302PyObject *
9303PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9304 Py_ssize_t length)
9305{
Victor Stinnerf0124502011-11-21 23:12:56 +01009306 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009307 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009308 Py_UCS4 maxchar;
9309 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009310 const void *data;
Victor Stinnerf0124502011-11-21 23:12:56 +01009311
Victor Stinner99d7ad02012-02-22 13:37:39 +01009312 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009313 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009314 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009315 if (ch > 127) {
9316 int decimal = Py_UNICODE_TODECIMAL(ch);
9317 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009318 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009319 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009320 }
9321 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009322
9323 /* Copy to a new string */
9324 decimal = PyUnicode_New(length, maxchar);
9325 if (decimal == NULL)
9326 return decimal;
9327 kind = PyUnicode_KIND(decimal);
9328 data = PyUnicode_DATA(decimal);
9329 /* Iterate over code points */
9330 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009331 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009332 if (ch > 127) {
9333 int decimal = Py_UNICODE_TODECIMAL(ch);
9334 if (decimal >= 0)
9335 ch = '0' + decimal;
9336 }
9337 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009339 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009340}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009341/* --- Decimal Encoder ---------------------------------------------------- */
9342
Alexander Belopolsky40018472011-02-26 01:02:56 +00009343int
9344PyUnicode_EncodeDecimal(Py_UNICODE *s,
9345 Py_ssize_t length,
9346 char *output,
9347 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009348{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009349 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009350 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009351 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009352 const void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009353
9354 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009355 PyErr_BadArgument();
9356 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009357 }
9358
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009359 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009360 if (unicode == NULL)
9361 return -1;
9362
Victor Stinner42bf7752011-11-21 22:52:58 +01009363 kind = PyUnicode_KIND(unicode);
9364 data = PyUnicode_DATA(unicode);
9365
Victor Stinnerb84d7232011-11-22 01:50:07 +01009366 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009367 PyObject *exc;
9368 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009369 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009370 Py_ssize_t startpos;
9371
9372 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009373
Benjamin Peterson29060642009-01-31 22:14:21 +00009374 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009375 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009376 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009377 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009378 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009379 decimal = Py_UNICODE_TODECIMAL(ch);
9380 if (decimal >= 0) {
9381 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009382 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009383 continue;
9384 }
9385 if (0 < ch && ch < 256) {
9386 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009387 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009388 continue;
9389 }
Victor Stinner6345be92011-11-25 20:09:01 +01009390
Victor Stinner42bf7752011-11-21 22:52:58 +01009391 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009392 exc = NULL;
9393 raise_encode_exception(&exc, "decimal", unicode,
9394 startpos, startpos+1,
9395 "invalid decimal Unicode string");
9396 Py_XDECREF(exc);
9397 Py_DECREF(unicode);
9398 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009399 }
9400 /* 0-terminate the output string */
9401 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009402 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009403 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009404}
9405
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406/* --- Helpers ------------------------------------------------------------ */
9407
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009408/* helper macro to fixup start/end slice values */
9409#define ADJUST_INDICES(start, end, len) \
9410 if (end > len) \
9411 end = len; \
9412 else if (end < 0) { \
9413 end += len; \
9414 if (end < 0) \
9415 end = 0; \
9416 } \
9417 if (start < 0) { \
9418 start += len; \
9419 if (start < 0) \
9420 start = 0; \
9421 }
9422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009424any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009426 Py_ssize_t end,
9427 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009428{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009429 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009430 const void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 Py_ssize_t len1, len2, result;
9432
9433 kind1 = PyUnicode_KIND(s1);
9434 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009435 if (kind1 < kind2)
9436 return -1;
9437
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438 len1 = PyUnicode_GET_LENGTH(s1);
9439 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009440 ADJUST_INDICES(start, end, len1);
9441 if (end - start < len2)
9442 return -1;
9443
9444 buf1 = PyUnicode_DATA(s1);
9445 buf2 = PyUnicode_DATA(s2);
9446 if (len2 == 1) {
9447 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9448 result = findchar((const char *)buf1 + kind1*start,
9449 kind1, end - start, ch, direction);
9450 if (result == -1)
9451 return -1;
9452 else
9453 return start + result;
9454 }
9455
9456 if (kind2 != kind1) {
Serhiy Storchaka17b47332020-04-01 15:41:49 +03009457 buf2 = unicode_askind(kind2, buf2, len2, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009458 if (!buf2)
9459 return -2;
9460 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461
Victor Stinner794d5672011-10-10 03:21:36 +02009462 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009463 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009464 case PyUnicode_1BYTE_KIND:
9465 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9466 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9467 else
9468 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9469 break;
9470 case PyUnicode_2BYTE_KIND:
9471 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9472 break;
9473 case PyUnicode_4BYTE_KIND:
9474 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9475 break;
9476 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009477 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009478 }
9479 }
9480 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009481 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009482 case PyUnicode_1BYTE_KIND:
9483 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9484 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9485 else
9486 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9487 break;
9488 case PyUnicode_2BYTE_KIND:
9489 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9490 break;
9491 case PyUnicode_4BYTE_KIND:
9492 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9493 break;
9494 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009495 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009496 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009497 }
9498
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009499 assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009500 if (kind2 != kind1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009501 PyMem_Free((void *)buf2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009502
9503 return result;
9504}
9505
Victor Stinner59423e32018-11-26 13:40:01 +01009506/* _PyUnicode_InsertThousandsGrouping() helper functions */
9507#include "stringlib/localeutil.h"
9508
9509/**
9510 * InsertThousandsGrouping:
9511 * @writer: Unicode writer.
9512 * @n_buffer: Number of characters in @buffer.
9513 * @digits: Digits we're reading from. If count is non-NULL, this is unused.
9514 * @d_pos: Start of digits string.
9515 * @n_digits: The number of digits in the string, in which we want
9516 * to put the grouping chars.
9517 * @min_width: The minimum width of the digits in the output string.
9518 * Output will be zero-padded on the left to fill.
9519 * @grouping: see definition in localeconv().
9520 * @thousands_sep: see definition in localeconv().
9521 *
9522 * There are 2 modes: counting and filling. If @writer is NULL,
9523 * we are in counting mode, else filling mode.
9524 * If counting, the required buffer size is returned.
9525 * If filling, we know the buffer will be large enough, so we don't
9526 * need to pass in the buffer size.
9527 * Inserts thousand grouping characters (as defined by grouping and
9528 * thousands_sep) into @writer.
9529 *
9530 * Return value: -1 on error, number of characters otherwise.
9531 **/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009533_PyUnicode_InsertThousandsGrouping(
Victor Stinner59423e32018-11-26 13:40:01 +01009534 _PyUnicodeWriter *writer,
Victor Stinner41a863c2012-02-24 00:37:51 +01009535 Py_ssize_t n_buffer,
Victor Stinner59423e32018-11-26 13:40:01 +01009536 PyObject *digits,
9537 Py_ssize_t d_pos,
9538 Py_ssize_t n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009539 Py_ssize_t min_width,
Victor Stinner59423e32018-11-26 13:40:01 +01009540 const char *grouping,
9541 PyObject *thousands_sep,
Victor Stinner41a863c2012-02-24 00:37:51 +01009542 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543{
Xtreak3f7983a2019-01-07 20:39:14 +05309544 min_width = Py_MAX(0, min_width);
Victor Stinner59423e32018-11-26 13:40:01 +01009545 if (writer) {
9546 assert(digits != NULL);
9547 assert(maxchar == NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009548 }
9549 else {
Victor Stinner59423e32018-11-26 13:40:01 +01009550 assert(digits == NULL);
9551 assert(maxchar != NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009552 }
Victor Stinner59423e32018-11-26 13:40:01 +01009553 assert(0 <= d_pos);
9554 assert(0 <= n_digits);
Victor Stinner59423e32018-11-26 13:40:01 +01009555 assert(grouping != NULL);
9556
9557 if (digits != NULL) {
9558 if (PyUnicode_READY(digits) == -1) {
9559 return -1;
Victor Stinner90f50d42012-02-24 01:44:47 +01009560 }
Victor Stinner59423e32018-11-26 13:40:01 +01009561 }
9562 if (PyUnicode_READY(thousands_sep) == -1) {
9563 return -1;
Victor Stinner41a863c2012-02-24 00:37:51 +01009564 }
9565
Victor Stinner59423e32018-11-26 13:40:01 +01009566 Py_ssize_t count = 0;
9567 Py_ssize_t n_zeros;
9568 int loop_broken = 0;
9569 int use_separator = 0; /* First time through, don't append the
9570 separator. They only go between
9571 groups. */
9572 Py_ssize_t buffer_pos;
9573 Py_ssize_t digits_pos;
9574 Py_ssize_t len;
9575 Py_ssize_t n_chars;
9576 Py_ssize_t remaining = n_digits; /* Number of chars remaining to
9577 be looked at */
9578 /* A generator that returns all of the grouping widths, until it
9579 returns 0. */
9580 GroupGenerator groupgen;
9581 GroupGenerator_init(&groupgen, grouping);
9582 const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9583
9584 /* if digits are not grouped, thousands separator
9585 should be an empty string */
9586 assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
9587
9588 digits_pos = d_pos + n_digits;
9589 if (writer) {
9590 buffer_pos = writer->pos + n_buffer;
9591 assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
9592 assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 }
Victor Stinner59423e32018-11-26 13:40:01 +01009594 else {
9595 buffer_pos = n_buffer;
Victor Stinner90f50d42012-02-24 01:44:47 +01009596 }
Victor Stinner59423e32018-11-26 13:40:01 +01009597
9598 if (!writer) {
Victor Stinner41a863c2012-02-24 00:37:51 +01009599 *maxchar = 127;
Victor Stinner41a863c2012-02-24 00:37:51 +01009600 }
Victor Stinner59423e32018-11-26 13:40:01 +01009601
9602 while ((len = GroupGenerator_next(&groupgen)) > 0) {
9603 len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
9604 n_zeros = Py_MAX(0, len - remaining);
9605 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9606
9607 /* Use n_zero zero's and n_chars chars */
9608
9609 /* Count only, don't do anything. */
9610 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9611
9612 /* Copy into the writer. */
9613 InsertThousandsGrouping_fill(writer, &buffer_pos,
9614 digits, &digits_pos,
9615 n_chars, n_zeros,
9616 use_separator ? thousands_sep : NULL,
9617 thousands_sep_len, maxchar);
9618
9619 /* Use a separator next time. */
9620 use_separator = 1;
9621
9622 remaining -= n_chars;
9623 min_width -= len;
9624
9625 if (remaining <= 0 && min_width <= 0) {
9626 loop_broken = 1;
9627 break;
9628 }
9629 min_width -= thousands_sep_len;
9630 }
9631 if (!loop_broken) {
9632 /* We left the loop without using a break statement. */
9633
9634 len = Py_MAX(Py_MAX(remaining, min_width), 1);
9635 n_zeros = Py_MAX(0, len - remaining);
9636 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9637
9638 /* Use n_zero zero's and n_chars chars */
9639 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9640
9641 /* Copy into the writer. */
9642 InsertThousandsGrouping_fill(writer, &buffer_pos,
9643 digits, &digits_pos,
9644 n_chars, n_zeros,
9645 use_separator ? thousands_sep : NULL,
9646 thousands_sep_len, maxchar);
9647 }
9648 return count;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009649}
9650
9651
Alexander Belopolsky40018472011-02-26 01:02:56 +00009652Py_ssize_t
9653PyUnicode_Count(PyObject *str,
9654 PyObject *substr,
9655 Py_ssize_t start,
9656 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009657{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009658 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009659 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009660 const void *buf1 = NULL, *buf2 = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009661 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009662
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009663 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009664 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009665
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009666 kind1 = PyUnicode_KIND(str);
9667 kind2 = PyUnicode_KIND(substr);
9668 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009669 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009670
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009671 len1 = PyUnicode_GET_LENGTH(str);
9672 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009673 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009674 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009675 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009676
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009677 buf1 = PyUnicode_DATA(str);
9678 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009679 if (kind2 != kind1) {
Serhiy Storchaka17b47332020-04-01 15:41:49 +03009680 buf2 = unicode_askind(kind2, buf2, len2, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009681 if (!buf2)
9682 goto onError;
9683 }
9684
9685 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009686 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009687 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009688 result = asciilib_count(
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009689 ((const Py_UCS1*)buf1) + start, end - start,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009690 buf2, len2, PY_SSIZE_T_MAX
9691 );
9692 else
9693 result = ucs1lib_count(
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009694 ((const Py_UCS1*)buf1) + start, end - start,
Victor Stinnerc3cec782011-10-05 21:24:08 +02009695 buf2, len2, PY_SSIZE_T_MAX
9696 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 break;
9698 case PyUnicode_2BYTE_KIND:
9699 result = ucs2lib_count(
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009700 ((const Py_UCS2*)buf1) + start, end - start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 buf2, len2, PY_SSIZE_T_MAX
9702 );
9703 break;
9704 case PyUnicode_4BYTE_KIND:
9705 result = ucs4lib_count(
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009706 ((const Py_UCS4*)buf1) + start, end - start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009707 buf2, len2, PY_SSIZE_T_MAX
9708 );
9709 break;
9710 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009711 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009712 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009713
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009714 assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009715 if (kind2 != kind1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009716 PyMem_Free((void *)buf2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009717
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 onError:
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009720 assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
9721 if (kind2 != kind1)
9722 PyMem_Free((void *)buf2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009723 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009724}
9725
Alexander Belopolsky40018472011-02-26 01:02:56 +00009726Py_ssize_t
9727PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009728 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009729 Py_ssize_t start,
9730 Py_ssize_t end,
9731 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009732{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009733 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009734 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009735
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009736 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009737}
9738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009739Py_ssize_t
9740PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9741 Py_ssize_t start, Py_ssize_t end,
9742 int direction)
9743{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009744 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009745 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009746 if (PyUnicode_READY(str) == -1)
9747 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009748 len = PyUnicode_GET_LENGTH(str);
9749 ADJUST_INDICES(start, end, len);
9750 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009751 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009752 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009753 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9754 kind, end-start, ch, direction);
9755 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009756 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009757 else
9758 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009759}
9760
Alexander Belopolsky40018472011-02-26 01:02:56 +00009761static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009762tailmatch(PyObject *self,
9763 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009764 Py_ssize_t start,
9765 Py_ssize_t end,
9766 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009767{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009768 int kind_self;
9769 int kind_sub;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009770 const void *data_self;
9771 const void *data_sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009772 Py_ssize_t offset;
9773 Py_ssize_t i;
9774 Py_ssize_t end_sub;
9775
9776 if (PyUnicode_READY(self) == -1 ||
9777 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009778 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009779
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009780 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9781 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009782 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009783 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009784
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009785 if (PyUnicode_GET_LENGTH(substring) == 0)
9786 return 1;
9787
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009788 kind_self = PyUnicode_KIND(self);
9789 data_self = PyUnicode_DATA(self);
9790 kind_sub = PyUnicode_KIND(substring);
9791 data_sub = PyUnicode_DATA(substring);
9792 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9793
9794 if (direction > 0)
9795 offset = end;
9796 else
9797 offset = start;
9798
9799 if (PyUnicode_READ(kind_self, data_self, offset) ==
9800 PyUnicode_READ(kind_sub, data_sub, 0) &&
9801 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9802 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9803 /* If both are of the same kind, memcmp is sufficient */
9804 if (kind_self == kind_sub) {
9805 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009806 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 data_sub,
9808 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009809 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009810 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009811 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 else {
9813 /* We do not need to compare 0 and len(substring)-1 because
9814 the if statement above ensured already that they are equal
9815 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009816 for (i = 1; i < end_sub; ++i) {
9817 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9818 PyUnicode_READ(kind_sub, data_sub, i))
9819 return 0;
9820 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009821 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009822 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009823 }
9824
9825 return 0;
9826}
9827
Alexander Belopolsky40018472011-02-26 01:02:56 +00009828Py_ssize_t
9829PyUnicode_Tailmatch(PyObject *str,
9830 PyObject *substr,
9831 Py_ssize_t start,
9832 Py_ssize_t end,
9833 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009834{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009835 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009836 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009837
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009838 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009839}
9840
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009841static PyObject *
9842ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009843{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009844 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009845 const char *data = PyUnicode_DATA(self);
9846 char *resdata;
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009847 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009848
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009849 res = PyUnicode_New(len, 127);
9850 if (res == NULL)
9851 return NULL;
9852 resdata = PyUnicode_DATA(res);
9853 if (lower)
9854 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009855 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009856 _Py_bytes_upper(resdata, data, len);
9857 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009858}
9859
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860static Py_UCS4
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009861handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009862{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009863 Py_ssize_t j;
9864 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009865 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009866 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009867
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009868 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9869
9870 where ! is a negation and \p{xxx} is a character with property xxx.
9871 */
9872 for (j = i - 1; j >= 0; j--) {
9873 c = PyUnicode_READ(kind, data, j);
9874 if (!_PyUnicode_IsCaseIgnorable(c))
9875 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009876 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009877 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9878 if (final_sigma) {
9879 for (j = i + 1; j < length; j++) {
9880 c = PyUnicode_READ(kind, data, j);
9881 if (!_PyUnicode_IsCaseIgnorable(c))
9882 break;
9883 }
9884 final_sigma = j == length || !_PyUnicode_IsCased(c);
9885 }
9886 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009887}
9888
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009889static int
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009890lower_ucs4(int kind, const void *data, Py_ssize_t length, Py_ssize_t i,
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009891 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009892{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009893 /* Obscure special case. */
9894 if (c == 0x3A3) {
9895 mapped[0] = handle_capital_sigma(kind, data, length, i);
9896 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009897 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009898 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899}
9900
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009901static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009902do_capitalize(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009903{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009904 Py_ssize_t i, k = 0;
9905 int n_res, j;
9906 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009907
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009908 c = PyUnicode_READ(kind, data, 0);
Kingsley Mb015fc82019-04-12 16:35:39 +01009909 n_res = _PyUnicode_ToTitleFull(c, mapped);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009910 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009911 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009912 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009913 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009914 for (i = 1; i < length; i++) {
9915 c = PyUnicode_READ(kind, data, i);
9916 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9917 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009918 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009919 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009920 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009921 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009922 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009923}
9924
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009925static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009926do_swapcase(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009927 Py_ssize_t i, k = 0;
9928
9929 for (i = 0; i < length; i++) {
9930 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9931 int n_res, j;
9932 if (Py_UNICODE_ISUPPER(c)) {
9933 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9934 }
9935 else if (Py_UNICODE_ISLOWER(c)) {
9936 n_res = _PyUnicode_ToUpperFull(c, mapped);
9937 }
9938 else {
9939 n_res = 1;
9940 mapped[0] = c;
9941 }
9942 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009943 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009944 res[k++] = mapped[j];
9945 }
9946 }
9947 return k;
9948}
9949
9950static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009951do_upper_or_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res,
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009952 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009953{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009954 Py_ssize_t i, k = 0;
9955
9956 for (i = 0; i < length; i++) {
9957 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9958 int n_res, j;
9959 if (lower)
9960 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9961 else
9962 n_res = _PyUnicode_ToUpperFull(c, mapped);
9963 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009964 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009965 res[k++] = mapped[j];
9966 }
9967 }
9968 return k;
9969}
9970
9971static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009972do_upper(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009973{
9974 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9975}
9976
9977static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009978do_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009979{
9980 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9981}
9982
Benjamin Petersone51757f2012-01-12 21:10:29 -05009983static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +03009984do_casefold(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Benjamin Petersond5890c82012-01-14 13:23:30 -05009985{
9986 Py_ssize_t i, k = 0;
9987
9988 for (i = 0; i < length; i++) {
9989 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9990 Py_UCS4 mapped[3];
9991 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9992 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009993 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009994 res[k++] = mapped[j];
9995 }
9996 }
9997 return k;
9998}
9999
10000static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010001do_title(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Benjamin Petersone51757f2012-01-12 21:10:29 -050010002{
10003 Py_ssize_t i, k = 0;
10004 int previous_is_cased;
10005
10006 previous_is_cased = 0;
10007 for (i = 0; i < length; i++) {
10008 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
10009 Py_UCS4 mapped[3];
10010 int n_res, j;
10011
10012 if (previous_is_cased)
10013 n_res = lower_ucs4(kind, data, length, i, c, mapped);
10014 else
10015 n_res = _PyUnicode_ToTitleFull(c, mapped);
10016
10017 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -070010018 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -050010019 res[k++] = mapped[j];
10020 }
10021
10022 previous_is_cased = _PyUnicode_IsCased(c);
10023 }
10024 return k;
10025}
10026
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010027static PyObject *
10028case_operation(PyObject *self,
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010029 Py_ssize_t (*perform)(int, const void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010030{
10031 PyObject *res = NULL;
10032 Py_ssize_t length, newlength = 0;
10033 int kind, outkind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010034 const void *data;
10035 void *outdata;
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010036 Py_UCS4 maxchar = 0, *tmp, *tmpend;
10037
Benjamin Petersoneea48462012-01-16 14:28:50 -050010038 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010039
10040 kind = PyUnicode_KIND(self);
10041 data = PyUnicode_DATA(self);
10042 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +020010043 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -040010044 PyErr_SetString(PyExc_OverflowError, "string is too long");
10045 return NULL;
10046 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -040010047 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010048 if (tmp == NULL)
10049 return PyErr_NoMemory();
10050 newlength = perform(kind, data, length, tmp, &maxchar);
10051 res = PyUnicode_New(newlength, maxchar);
10052 if (res == NULL)
10053 goto leave;
10054 tmpend = tmp + newlength;
10055 outdata = PyUnicode_DATA(res);
10056 outkind = PyUnicode_KIND(res);
10057 switch (outkind) {
10058 case PyUnicode_1BYTE_KIND:
10059 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
10060 break;
10061 case PyUnicode_2BYTE_KIND:
10062 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
10063 break;
10064 case PyUnicode_4BYTE_KIND:
10065 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
10066 break;
10067 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010068 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010069 }
10070 leave:
10071 PyMem_FREE(tmp);
10072 return res;
10073}
10074
Tim Peters8ce9f162004-08-27 01:49:32 +000010075PyObject *
10076PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010077{
Serhiy Storchakaea525a22016-09-06 22:07:53 +030010078 PyObject *res;
10079 PyObject *fseq;
10080 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010081 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010082
Benjamin Peterson9743b2c2014-02-15 13:02:52 -050010083 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +000010084 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010085 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +000010086 }
10087
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010088 /* NOTE: the following code can't call back into Python code,
10089 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +000010090 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010091
Serhiy Storchakaea525a22016-09-06 22:07:53 +030010092 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +000010093 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +030010094 res = _PyUnicode_JoinArray(separator, items, seqlen);
10095 Py_DECREF(fseq);
10096 return res;
10097}
10098
10099PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +020010100_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +030010101{
10102 PyObject *res = NULL; /* the result */
10103 PyObject *sep = NULL;
10104 Py_ssize_t seplen;
10105 PyObject *item;
10106 Py_ssize_t sz, i, res_offset;
10107 Py_UCS4 maxchar;
10108 Py_UCS4 item_maxchar;
10109 int use_memcpy;
10110 unsigned char *res_data = NULL, *sep_data = NULL;
10111 PyObject *last_obj;
10112 unsigned int kind = 0;
10113
Tim Peters05eba1f2004-08-27 21:32:02 +000010114 /* If empty sequence, return u"". */
10115 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010116 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +000010117 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010118
Tim Peters05eba1f2004-08-27 21:32:02 +000010119 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010120 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +020010121 if (seqlen == 1) {
10122 if (PyUnicode_CheckExact(items[0])) {
10123 res = items[0];
10124 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +020010125 return res;
10126 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010127 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +020010128 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +000010129 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010130 else {
Victor Stinneracf47b82011-10-06 12:32:37 +020010131 /* Set up sep and seplen */
10132 if (separator == NULL) {
10133 /* fall back to a blank space separator */
10134 sep = PyUnicode_FromOrdinal(' ');
10135 if (!sep)
10136 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +020010137 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +020010138 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +000010139 }
Victor Stinneracf47b82011-10-06 12:32:37 +020010140 else {
10141 if (!PyUnicode_Check(separator)) {
10142 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020010143 "separator: expected str instance,"
10144 " %.80s found",
10145 Py_TYPE(separator)->tp_name);
Victor Stinneracf47b82011-10-06 12:32:37 +020010146 goto onError;
10147 }
10148 if (PyUnicode_READY(separator))
10149 goto onError;
10150 sep = separator;
10151 seplen = PyUnicode_GET_LENGTH(separator);
10152 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
10153 /* inc refcount to keep this code path symmetric with the
10154 above case of a blank separator */
10155 Py_INCREF(sep);
10156 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010157 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010158 }
10159
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010160 /* There are at least two things to join, or else we have a subclass
10161 * of str in the sequence.
10162 * Do a pre-pass to figure out the total amount of space we'll
10163 * need (sz), and see whether all argument are strings.
10164 */
10165 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010166#ifdef Py_DEBUG
10167 use_memcpy = 0;
10168#else
10169 use_memcpy = 1;
10170#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010171 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010172 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010173 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010174 if (!PyUnicode_Check(item)) {
10175 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020010176 "sequence item %zd: expected str instance,"
10177 " %.80s found",
10178 i, Py_TYPE(item)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000010179 goto onError;
10180 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 if (PyUnicode_READY(item) == -1)
10182 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010183 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010185 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010186 if (i != 0) {
10187 add_sz += seplen;
10188 }
10189 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010190 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010191 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010192 goto onError;
10193 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010194 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010195 if (use_memcpy && last_obj != NULL) {
10196 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10197 use_memcpy = 0;
10198 }
10199 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010200 }
Tim Petersced69f82003-09-16 20:30:58 +000010201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010203 if (res == NULL)
10204 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010205
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010206 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010207#ifdef Py_DEBUG
10208 use_memcpy = 0;
10209#else
10210 if (use_memcpy) {
10211 res_data = PyUnicode_1BYTE_DATA(res);
10212 kind = PyUnicode_KIND(res);
10213 if (seplen != 0)
10214 sep_data = PyUnicode_1BYTE_DATA(sep);
10215 }
10216#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010217 if (use_memcpy) {
10218 for (i = 0; i < seqlen; ++i) {
10219 Py_ssize_t itemlen;
10220 item = items[i];
10221
10222 /* Copy item, and maybe the separator. */
10223 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010224 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010225 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010226 kind * seplen);
10227 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010228 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010229
10230 itemlen = PyUnicode_GET_LENGTH(item);
10231 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010232 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010233 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010234 kind * itemlen);
10235 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010236 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010237 }
10238 assert(res_data == PyUnicode_1BYTE_DATA(res)
10239 + kind * PyUnicode_GET_LENGTH(res));
10240 }
10241 else {
10242 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10243 Py_ssize_t itemlen;
10244 item = items[i];
10245
10246 /* Copy item, and maybe the separator. */
10247 if (i && seplen != 0) {
10248 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10249 res_offset += seplen;
10250 }
10251
10252 itemlen = PyUnicode_GET_LENGTH(item);
10253 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010254 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010255 res_offset += itemlen;
10256 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010257 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010258 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010259 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010260
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010262 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010264
Benjamin Peterson29060642009-01-31 22:14:21 +000010265 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010267 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010268 return NULL;
10269}
10270
Victor Stinnerd3f08822012-05-29 12:57:52 +020010271void
10272_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10273 Py_UCS4 fill_char)
10274{
10275 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Victor Stinner163403a2018-11-27 12:41:17 +010010276 void *data = PyUnicode_DATA(unicode);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010277 assert(PyUnicode_IS_READY(unicode));
10278 assert(unicode_modifiable(unicode));
10279 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10280 assert(start >= 0);
10281 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner59423e32018-11-26 13:40:01 +010010282 unicode_fill(kind, data, fill_char, start, length);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010283}
10284
Victor Stinner3fe55312012-01-04 00:33:50 +010010285Py_ssize_t
10286PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10287 Py_UCS4 fill_char)
10288{
10289 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010290
10291 if (!PyUnicode_Check(unicode)) {
10292 PyErr_BadInternalCall();
10293 return -1;
10294 }
10295 if (PyUnicode_READY(unicode) == -1)
10296 return -1;
10297 if (unicode_check_modifiable(unicode))
10298 return -1;
10299
Victor Stinnerd3f08822012-05-29 12:57:52 +020010300 if (start < 0) {
10301 PyErr_SetString(PyExc_IndexError, "string index out of range");
10302 return -1;
10303 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010304 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10305 PyErr_SetString(PyExc_ValueError,
10306 "fill character is bigger than "
10307 "the string maximum character");
10308 return -1;
10309 }
10310
10311 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10312 length = Py_MIN(maxlen, length);
10313 if (length <= 0)
10314 return 0;
10315
Victor Stinnerd3f08822012-05-29 12:57:52 +020010316 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010317 return length;
10318}
10319
Victor Stinner9310abb2011-10-05 00:59:23 +020010320static PyObject *
10321pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010322 Py_ssize_t left,
10323 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010325{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 PyObject *u;
10327 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010328 int kind;
10329 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010330
10331 if (left < 0)
10332 left = 0;
10333 if (right < 0)
10334 right = 0;
10335
Victor Stinnerc4b49542011-12-11 22:44:26 +010010336 if (left == 0 && right == 0)
10337 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10340 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010341 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10342 return NULL;
10343 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010345 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010347 if (!u)
10348 return NULL;
10349
10350 kind = PyUnicode_KIND(u);
10351 data = PyUnicode_DATA(u);
10352 if (left)
Victor Stinner59423e32018-11-26 13:40:01 +010010353 unicode_fill(kind, data, fill, 0, left);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010354 if (right)
Victor Stinner59423e32018-11-26 13:40:01 +010010355 unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010356 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010357 assert(_PyUnicode_CheckConsistency(u, 1));
10358 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010359}
10360
Alexander Belopolsky40018472011-02-26 01:02:56 +000010361PyObject *
10362PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010363{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010364 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010365
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010366 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010367 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010368
Benjamin Petersonead6b532011-12-20 17:23:42 -060010369 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010370 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010371 if (PyUnicode_IS_ASCII(string))
10372 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010373 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010374 PyUnicode_GET_LENGTH(string), keepends);
10375 else
10376 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010377 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010378 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 break;
10380 case PyUnicode_2BYTE_KIND:
10381 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010382 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 PyUnicode_GET_LENGTH(string), keepends);
10384 break;
10385 case PyUnicode_4BYTE_KIND:
10386 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010387 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010388 PyUnicode_GET_LENGTH(string), keepends);
10389 break;
10390 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010391 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010393 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394}
10395
Alexander Belopolsky40018472011-02-26 01:02:56 +000010396static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010397split(PyObject *self,
10398 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010399 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010401 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010402 const void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 Py_ssize_t len1, len2;
10404 PyObject* out;
10405
Guido van Rossumd57fd912000-03-10 22:53:23 +000010406 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010407 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010408
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 if (PyUnicode_READY(self) == -1)
10410 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010411
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010413 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010415 if (PyUnicode_IS_ASCII(self))
10416 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010417 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010418 PyUnicode_GET_LENGTH(self), maxcount
10419 );
10420 else
10421 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010422 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010423 PyUnicode_GET_LENGTH(self), maxcount
10424 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 case PyUnicode_2BYTE_KIND:
10426 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010427 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 PyUnicode_GET_LENGTH(self), maxcount
10429 );
10430 case PyUnicode_4BYTE_KIND:
10431 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010432 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 PyUnicode_GET_LENGTH(self), maxcount
10434 );
10435 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010436 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 }
10438
10439 if (PyUnicode_READY(substring) == -1)
10440 return NULL;
10441
10442 kind1 = PyUnicode_KIND(self);
10443 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 len1 = PyUnicode_GET_LENGTH(self);
10445 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010446 if (kind1 < kind2 || len1 < len2) {
10447 out = PyList_New(1);
10448 if (out == NULL)
10449 return NULL;
10450 Py_INCREF(self);
10451 PyList_SET_ITEM(out, 0, self);
10452 return out;
10453 }
10454 buf1 = PyUnicode_DATA(self);
10455 buf2 = PyUnicode_DATA(substring);
10456 if (kind2 != kind1) {
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010457 buf2 = unicode_askind(kind2, buf2, len2, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010458 if (!buf2)
10459 return NULL;
10460 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010461
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010462 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010464 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10465 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010466 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010467 else
10468 out = ucs1lib_split(
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_2BYTE_KIND:
10472 out = ucs2lib_split(
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 case PyUnicode_4BYTE_KIND:
10476 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010477 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010478 break;
10479 default:
10480 out = NULL;
10481 }
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010482 assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010483 if (kind2 != kind1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010484 PyMem_Free((void *)buf2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486}
10487
Alexander Belopolsky40018472011-02-26 01:02:56 +000010488static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010489rsplit(PyObject *self,
10490 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010491 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010492{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010493 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010494 const void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010495 Py_ssize_t len1, len2;
10496 PyObject* out;
10497
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010498 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010499 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 if (PyUnicode_READY(self) == -1)
10502 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010503
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010504 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010505 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010507 if (PyUnicode_IS_ASCII(self))
10508 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010509 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010510 PyUnicode_GET_LENGTH(self), maxcount
10511 );
10512 else
10513 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010514 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010515 PyUnicode_GET_LENGTH(self), maxcount
10516 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 case PyUnicode_2BYTE_KIND:
10518 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010519 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 PyUnicode_GET_LENGTH(self), maxcount
10521 );
10522 case PyUnicode_4BYTE_KIND:
10523 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010524 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 PyUnicode_GET_LENGTH(self), maxcount
10526 );
10527 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010528 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 }
10530
10531 if (PyUnicode_READY(substring) == -1)
10532 return NULL;
10533
10534 kind1 = PyUnicode_KIND(self);
10535 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 len1 = PyUnicode_GET_LENGTH(self);
10537 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010538 if (kind1 < kind2 || len1 < len2) {
10539 out = PyList_New(1);
10540 if (out == NULL)
10541 return NULL;
10542 Py_INCREF(self);
10543 PyList_SET_ITEM(out, 0, self);
10544 return out;
10545 }
10546 buf1 = PyUnicode_DATA(self);
10547 buf2 = PyUnicode_DATA(substring);
10548 if (kind2 != kind1) {
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010549 buf2 = unicode_askind(kind2, buf2, len2, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010550 if (!buf2)
10551 return NULL;
10552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010554 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010556 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10557 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010558 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010559 else
10560 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010561 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010562 break;
10563 case PyUnicode_2BYTE_KIND:
10564 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010565 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 break;
10567 case PyUnicode_4BYTE_KIND:
10568 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010569 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 break;
10571 default:
10572 out = NULL;
10573 }
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010574 assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010575 if (kind2 != kind1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010576 PyMem_Free((void *)buf2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 return out;
10578}
10579
10580static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010581anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
10582 PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010584 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010586 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10587 return asciilib_find(buf1, len1, buf2, len2, offset);
10588 else
10589 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 case PyUnicode_2BYTE_KIND:
10591 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10592 case PyUnicode_4BYTE_KIND:
10593 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10594 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010595 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596}
10597
10598static Py_ssize_t
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010599anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
10600 PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010602 switch (kind) {
10603 case PyUnicode_1BYTE_KIND:
10604 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10605 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10606 else
10607 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10608 case PyUnicode_2BYTE_KIND:
10609 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10610 case PyUnicode_4BYTE_KIND:
10611 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10612 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010613 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010614}
10615
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010616static void
10617replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10618 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10619{
10620 int kind = PyUnicode_KIND(u);
10621 void *data = PyUnicode_DATA(u);
10622 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10623 if (kind == PyUnicode_1BYTE_KIND) {
10624 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10625 (Py_UCS1 *)data + len,
10626 u1, u2, maxcount);
10627 }
10628 else if (kind == PyUnicode_2BYTE_KIND) {
10629 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10630 (Py_UCS2 *)data + len,
10631 u1, u2, maxcount);
10632 }
10633 else {
10634 assert(kind == PyUnicode_4BYTE_KIND);
10635 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10636 (Py_UCS4 *)data + len,
10637 u1, u2, maxcount);
10638 }
10639}
10640
Alexander Belopolsky40018472011-02-26 01:02:56 +000010641static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010642replace(PyObject *self, PyObject *str1,
10643 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 PyObject *u;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010646 const char *sbuf = PyUnicode_DATA(self);
10647 const void *buf1 = PyUnicode_DATA(str1);
10648 const void *buf2 = PyUnicode_DATA(str2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 int srelease = 0, release1 = 0, release2 = 0;
10650 int skind = PyUnicode_KIND(self);
10651 int kind1 = PyUnicode_KIND(str1);
10652 int kind2 = PyUnicode_KIND(str2);
10653 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10654 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10655 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010656 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010657 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010658
Serhiy Storchaka865c3b22019-10-30 12:03:53 +020010659 if (slen < len1)
10660 goto nothing;
10661
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010663 maxcount = PY_SSIZE_T_MAX;
Serhiy Storchaka865c3b22019-10-30 12:03:53 +020010664 else if (maxcount == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010665 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010666
Victor Stinner59de0ee2011-10-07 10:01:28 +020010667 if (str1 == str2)
10668 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669
Victor Stinner49a0a212011-10-12 23:46:10 +020010670 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010671 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10672 if (maxchar < maxchar_str1)
10673 /* substring too wide to be present */
10674 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010675 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10676 /* Replacing str1 with str2 may cause a maxchar reduction in the
10677 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010678 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010679 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010680
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010682 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010684 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010685 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010686 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010687 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010688 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010689
Victor Stinner69ed0f42013-04-09 21:48:24 +020010690 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010691 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010692 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010693 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010694 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010695 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010696 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010697 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010698
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010699 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10700 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010701 }
10702 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010703 int rkind = skind;
10704 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010705 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 if (kind1 < rkind) {
10708 /* widen substring */
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010709 buf1 = unicode_askind(kind1, buf1, len1, rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010710 if (!buf1) goto error;
10711 release1 = 1;
10712 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010713 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010714 if (i < 0)
10715 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010716 if (rkind > kind2) {
10717 /* widen replacement */
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010718 buf2 = unicode_askind(kind2, buf2, len2, rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010719 if (!buf2) goto error;
10720 release2 = 1;
10721 }
10722 else if (rkind < kind2) {
10723 /* widen self and buf1 */
10724 rkind = kind2;
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010725 if (release1) {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010726 assert(buf1 != PyUnicode_DATA(str1));
10727 PyMem_Free((void *)buf1);
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010728 buf1 = PyUnicode_DATA(str1);
10729 release1 = 0;
10730 }
10731 sbuf = unicode_askind(skind, sbuf, slen, rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 if (!sbuf) goto error;
10733 srelease = 1;
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010734 buf1 = unicode_askind(kind1, buf1, len1, rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 if (!buf1) goto error;
10736 release1 = 1;
10737 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010738 u = PyUnicode_New(slen, maxchar);
10739 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010740 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010741 assert(PyUnicode_KIND(u) == rkind);
10742 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010743
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010744 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010745 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010746 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010747 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010748 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010749 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010750
10751 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010752 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010753 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010754 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010755 if (i == -1)
10756 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010757 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010758 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010759 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010760 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010761 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010763 }
10764 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010765 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010766 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010767 int rkind = skind;
10768 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010770 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010771 /* widen substring */
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010772 buf1 = unicode_askind(kind1, buf1, len1, rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010773 if (!buf1) goto error;
10774 release1 = 1;
10775 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010776 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010777 if (n == 0)
10778 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010780 /* widen replacement */
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010781 buf2 = unicode_askind(kind2, buf2, len2, rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 if (!buf2) goto error;
10783 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010784 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010786 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 rkind = kind2;
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010788 sbuf = unicode_askind(skind, sbuf, slen, rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 if (!sbuf) goto error;
10790 srelease = 1;
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010791 if (release1) {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010792 assert(buf1 != PyUnicode_DATA(str1));
10793 PyMem_Free((void *)buf1);
Serhiy Storchaka17b47332020-04-01 15:41:49 +030010794 buf1 = PyUnicode_DATA(str1);
10795 release1 = 0;
10796 }
10797 buf1 = unicode_askind(kind1, buf1, len1, rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010798 if (!buf1) goto error;
10799 release1 = 1;
10800 }
10801 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10802 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010803 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010804 PyErr_SetString(PyExc_OverflowError,
10805 "replace string is too long");
10806 goto error;
10807 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010808 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010809 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010810 _Py_INCREF_UNICODE_EMPTY();
10811 if (!unicode_empty)
10812 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010813 u = unicode_empty;
10814 goto done;
10815 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010816 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010817 PyErr_SetString(PyExc_OverflowError,
10818 "replace string is too long");
10819 goto error;
10820 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010821 u = PyUnicode_New(new_size, maxchar);
10822 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010823 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010824 assert(PyUnicode_KIND(u) == rkind);
10825 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010826 ires = i = 0;
10827 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010828 while (n-- > 0) {
10829 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010830 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010831 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010832 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010833 if (j == -1)
10834 break;
10835 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010836 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010837 memcpy(res + rkind * ires,
10838 sbuf + rkind * i,
10839 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010840 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010841 }
10842 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010843 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010844 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010845 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010846 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010847 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010848 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010849 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010850 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010851 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010852 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010853 memcpy(res + rkind * ires,
10854 sbuf + rkind * i,
10855 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010856 }
10857 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010858 /* interleave */
10859 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010860 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010861 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010862 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010863 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010864 if (--n <= 0)
10865 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010866 memcpy(res + rkind * ires,
10867 sbuf + rkind * i,
10868 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010869 ires++;
10870 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010871 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010872 memcpy(res + rkind * ires,
10873 sbuf + rkind * i,
10874 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010875 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010876 }
10877
10878 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010879 unicode_adjust_maxchar(&u);
10880 if (u == NULL)
10881 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010882 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010883
10884 done:
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010885 assert(srelease == (sbuf != PyUnicode_DATA(self)));
10886 assert(release1 == (buf1 != PyUnicode_DATA(str1)));
10887 assert(release2 == (buf2 != PyUnicode_DATA(str2)));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010888 if (srelease)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010889 PyMem_FREE((void *)sbuf);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010890 if (release1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010891 PyMem_FREE((void *)buf1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010892 if (release2)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010893 PyMem_FREE((void *)buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010894 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010895 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010896
Benjamin Peterson29060642009-01-31 22:14:21 +000010897 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010898 /* nothing to replace; return original string (when possible) */
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010899 assert(srelease == (sbuf != PyUnicode_DATA(self)));
10900 assert(release1 == (buf1 != PyUnicode_DATA(str1)));
10901 assert(release2 == (buf2 != PyUnicode_DATA(str2)));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010902 if (srelease)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010903 PyMem_FREE((void *)sbuf);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010904 if (release1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010905 PyMem_FREE((void *)buf1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010906 if (release2)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010907 PyMem_FREE((void *)buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010908 return unicode_result_unchanged(self);
10909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010910 error:
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030010911 assert(srelease == (sbuf != PyUnicode_DATA(self)));
10912 assert(release1 == (buf1 != PyUnicode_DATA(str1)));
10913 assert(release2 == (buf2 != PyUnicode_DATA(str2)));
10914 if (srelease)
10915 PyMem_FREE((void *)sbuf);
10916 if (release1)
10917 PyMem_FREE((void *)buf1);
10918 if (release2)
10919 PyMem_FREE((void *)buf2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010920 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921}
10922
10923/* --- Unicode Object Methods --------------------------------------------- */
10924
INADA Naoki3ae20562017-01-16 20:41:20 +090010925/*[clinic input]
10926str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927
INADA Naoki3ae20562017-01-16 20:41:20 +090010928Return a version of the string where each word is titlecased.
10929
10930More specifically, words start with uppercased characters and all remaining
10931cased characters have lower case.
10932[clinic start generated code]*/
10933
10934static PyObject *
10935unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010936/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010938 if (PyUnicode_READY(self) == -1)
10939 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010940 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941}
10942
INADA Naoki3ae20562017-01-16 20:41:20 +090010943/*[clinic input]
10944str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945
INADA Naoki3ae20562017-01-16 20:41:20 +090010946Return a capitalized version of the string.
10947
10948More specifically, make the first character have upper case and the rest lower
10949case.
10950[clinic start generated code]*/
10951
10952static PyObject *
10953unicode_capitalize_impl(PyObject *self)
10954/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010956 if (PyUnicode_READY(self) == -1)
10957 return NULL;
10958 if (PyUnicode_GET_LENGTH(self) == 0)
10959 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010960 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010961}
10962
INADA Naoki3ae20562017-01-16 20:41:20 +090010963/*[clinic input]
10964str.casefold as unicode_casefold
10965
10966Return a version of the string suitable for caseless comparisons.
10967[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010968
10969static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010970unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010971/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010972{
10973 if (PyUnicode_READY(self) == -1)
10974 return NULL;
10975 if (PyUnicode_IS_ASCII(self))
10976 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010977 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010978}
10979
10980
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010981/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010982
10983static int
10984convert_uc(PyObject *obj, void *addr)
10985{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010986 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010987
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010988 if (!PyUnicode_Check(obj)) {
10989 PyErr_Format(PyExc_TypeError,
10990 "The fill character must be a unicode character, "
Victor Stinner998b8062018-09-12 00:23:25 +020010991 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010992 return 0;
10993 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010994 if (PyUnicode_READY(obj) < 0)
10995 return 0;
10996 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010997 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010998 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010999 return 0;
11000 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011001 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000011002 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011003}
11004
INADA Naoki3ae20562017-01-16 20:41:20 +090011005/*[clinic input]
11006str.center as unicode_center
11007
11008 width: Py_ssize_t
11009 fillchar: Py_UCS4 = ' '
11010 /
11011
11012Return a centered string of length width.
11013
11014Padding is done using the specified fill character (default is a space).
11015[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016
11017static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011018unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
11019/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011020{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011021 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022
Benjamin Petersonbac79492012-01-14 13:34:47 -050011023 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011024 return NULL;
11025
Victor Stinnerc4b49542011-12-11 22:44:26 +010011026 if (PyUnicode_GET_LENGTH(self) >= width)
11027 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028
Victor Stinnerc4b49542011-12-11 22:44:26 +010011029 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030 left = marg / 2 + (marg & width & 1);
11031
Victor Stinner9310abb2011-10-05 00:59:23 +020011032 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033}
11034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011035/* This function assumes that str1 and str2 are readied by the caller. */
11036
Marc-André Lemburge5034372000-08-08 08:04:29 +000011037static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011038unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000011039{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011040#define COMPARE(TYPE1, TYPE2) \
11041 do { \
11042 TYPE1* p1 = (TYPE1 *)data1; \
11043 TYPE2* p2 = (TYPE2 *)data2; \
11044 TYPE1* end = p1 + len; \
11045 Py_UCS4 c1, c2; \
11046 for (; p1 != end; p1++, p2++) { \
11047 c1 = *p1; \
11048 c2 = *p2; \
11049 if (c1 != c2) \
11050 return (c1 < c2) ? -1 : 1; \
11051 } \
11052 } \
11053 while (0)
11054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011055 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011056 const void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011057 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000011058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011059 kind1 = PyUnicode_KIND(str1);
11060 kind2 = PyUnicode_KIND(str2);
11061 data1 = PyUnicode_DATA(str1);
11062 data2 = PyUnicode_DATA(str2);
11063 len1 = PyUnicode_GET_LENGTH(str1);
11064 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020011065 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000011066
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011067 switch(kind1) {
11068 case PyUnicode_1BYTE_KIND:
11069 {
11070 switch(kind2) {
11071 case PyUnicode_1BYTE_KIND:
11072 {
11073 int cmp = memcmp(data1, data2, len);
11074 /* normalize result of memcmp() into the range [-1; 1] */
11075 if (cmp < 0)
11076 return -1;
11077 if (cmp > 0)
11078 return 1;
11079 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020011080 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011081 case PyUnicode_2BYTE_KIND:
11082 COMPARE(Py_UCS1, Py_UCS2);
11083 break;
11084 case PyUnicode_4BYTE_KIND:
11085 COMPARE(Py_UCS1, Py_UCS4);
11086 break;
11087 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011088 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011089 }
11090 break;
11091 }
11092 case PyUnicode_2BYTE_KIND:
11093 {
11094 switch(kind2) {
11095 case PyUnicode_1BYTE_KIND:
11096 COMPARE(Py_UCS2, Py_UCS1);
11097 break;
11098 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020011099 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011100 COMPARE(Py_UCS2, Py_UCS2);
11101 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020011102 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011103 case PyUnicode_4BYTE_KIND:
11104 COMPARE(Py_UCS2, Py_UCS4);
11105 break;
11106 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011107 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011108 }
11109 break;
11110 }
11111 case PyUnicode_4BYTE_KIND:
11112 {
11113 switch(kind2) {
11114 case PyUnicode_1BYTE_KIND:
11115 COMPARE(Py_UCS4, Py_UCS1);
11116 break;
11117 case PyUnicode_2BYTE_KIND:
11118 COMPARE(Py_UCS4, Py_UCS2);
11119 break;
11120 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020011121 {
11122#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
11123 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
11124 /* normalize result of wmemcmp() into the range [-1; 1] */
11125 if (cmp < 0)
11126 return -1;
11127 if (cmp > 0)
11128 return 1;
11129#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011130 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020011131#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011132 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020011133 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011134 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011135 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011136 }
11137 break;
11138 }
11139 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011140 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000011141 }
11142
Victor Stinner770e19e2012-10-04 22:59:45 +020011143 if (len1 == len2)
11144 return 0;
11145 if (len1 < len2)
11146 return -1;
11147 else
11148 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020011149
11150#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000011151}
11152
Benjamin Peterson621b4302016-09-09 13:54:34 -070011153static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020011154unicode_compare_eq(PyObject *str1, PyObject *str2)
11155{
11156 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011157 const void *data1, *data2;
Victor Stinnere5567ad2012-10-23 02:48:49 +020011158 Py_ssize_t len;
11159 int cmp;
11160
Victor Stinnere5567ad2012-10-23 02:48:49 +020011161 len = PyUnicode_GET_LENGTH(str1);
11162 if (PyUnicode_GET_LENGTH(str2) != len)
11163 return 0;
11164 kind = PyUnicode_KIND(str1);
11165 if (PyUnicode_KIND(str2) != kind)
11166 return 0;
11167 data1 = PyUnicode_DATA(str1);
11168 data2 = PyUnicode_DATA(str2);
11169
11170 cmp = memcmp(data1, data2, len * kind);
11171 return (cmp == 0);
11172}
11173
11174
Alexander Belopolsky40018472011-02-26 01:02:56 +000011175int
11176PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011178 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11179 if (PyUnicode_READY(left) == -1 ||
11180 PyUnicode_READY(right) == -1)
11181 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011182
11183 /* a string is equal to itself */
11184 if (left == right)
11185 return 0;
11186
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011187 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011188 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011189 PyErr_Format(PyExc_TypeError,
11190 "Can't compare %.100s and %.100s",
Victor Stinner58ac7002020-02-07 03:04:21 +010011191 Py_TYPE(left)->tp_name,
11192 Py_TYPE(right)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193 return -1;
11194}
11195
Martin v. Löwis5b222132007-06-10 09:51:05 +000011196int
11197PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11198{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011199 Py_ssize_t i;
11200 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011202 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011203
Victor Stinner910337b2011-10-03 03:20:16 +020011204 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011205 if (!PyUnicode_IS_READY(uni)) {
11206 const wchar_t *ws = _PyUnicode_WSTR(uni);
11207 /* Compare Unicode string and source character set string */
11208 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11209 if (chr != ustr[i])
11210 return (chr < ustr[i]) ? -1 : 1;
11211 }
11212 /* This check keeps Python strings that end in '\0' from comparing equal
11213 to C strings identical up to that point. */
11214 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11215 return 1; /* uni is longer */
11216 if (ustr[i])
11217 return -1; /* str is longer */
11218 return 0;
11219 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011220 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011221 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011222 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011223 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011224 size_t len, len2 = strlen(str);
11225 int cmp;
11226
11227 len = Py_MIN(len1, len2);
11228 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011229 if (cmp != 0) {
11230 if (cmp < 0)
11231 return -1;
11232 else
11233 return 1;
11234 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011235 if (len1 > len2)
11236 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011237 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011238 return -1; /* str is longer */
11239 return 0;
11240 }
11241 else {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011242 const void *data = PyUnicode_DATA(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011243 /* Compare Unicode string and source character set string */
11244 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011245 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011246 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11247 /* This check keeps Python strings that end in '\0' from comparing equal
11248 to C strings identical up to that point. */
11249 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11250 return 1; /* uni is longer */
11251 if (str[i])
11252 return -1; /* str is longer */
11253 return 0;
11254 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011255}
11256
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011257static int
11258non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11259{
11260 size_t i, len;
11261 const wchar_t *p;
11262 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11263 if (strlen(str) != len)
11264 return 0;
11265 p = _PyUnicode_WSTR(unicode);
11266 assert(p);
11267 for (i = 0; i < len; i++) {
11268 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011269 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011270 return 0;
11271 }
11272 return 1;
11273}
11274
11275int
11276_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11277{
11278 size_t len;
11279 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011280 assert(str);
11281#ifndef NDEBUG
11282 for (const char *p = str; *p; p++) {
11283 assert((unsigned char)*p < 128);
11284 }
11285#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011286 if (PyUnicode_READY(unicode) == -1) {
11287 /* Memory error or bad data */
11288 PyErr_Clear();
11289 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11290 }
11291 if (!PyUnicode_IS_ASCII(unicode))
11292 return 0;
11293 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11294 return strlen(str) == len &&
11295 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11296}
11297
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011298int
11299_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11300{
11301 PyObject *right_uni;
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011302
11303 assert(_PyUnicode_CHECK(left));
11304 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011305#ifndef NDEBUG
11306 for (const char *p = right->string; *p; p++) {
11307 assert((unsigned char)*p < 128);
11308 }
11309#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011310
11311 if (PyUnicode_READY(left) == -1) {
11312 /* memory error or bad data */
11313 PyErr_Clear();
11314 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11315 }
11316
11317 if (!PyUnicode_IS_ASCII(left))
11318 return 0;
11319
11320 right_uni = _PyUnicode_FromId(right); /* borrowed */
11321 if (right_uni == NULL) {
11322 /* memory error or bad data */
11323 PyErr_Clear();
11324 return _PyUnicode_EqualToASCIIString(left, right->string);
11325 }
11326
11327 if (left == right_uni)
11328 return 1;
11329
11330 if (PyUnicode_CHECK_INTERNED(left))
11331 return 0;
11332
Victor Stinner607b1022020-05-05 18:50:30 +020011333#ifdef INTERNED_STRINGS
INADA Naoki7cc95f52018-01-28 02:07:09 +090011334 assert(_PyUnicode_HASH(right_uni) != -1);
Victor Stinner607b1022020-05-05 18:50:30 +020011335 Py_hash_t hash = _PyUnicode_HASH(left);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011336 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11337 return 0;
Victor Stinner607b1022020-05-05 18:50:30 +020011338#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011339
11340 return unicode_compare_eq(left, right_uni);
11341}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011342
Alexander Belopolsky40018472011-02-26 01:02:56 +000011343PyObject *
11344PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011345{
11346 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011347
Victor Stinnere5567ad2012-10-23 02:48:49 +020011348 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11349 Py_RETURN_NOTIMPLEMENTED;
11350
11351 if (PyUnicode_READY(left) == -1 ||
11352 PyUnicode_READY(right) == -1)
11353 return NULL;
11354
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011355 if (left == right) {
11356 switch (op) {
11357 case Py_EQ:
11358 case Py_LE:
11359 case Py_GE:
11360 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011361 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011362 case Py_NE:
11363 case Py_LT:
11364 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011365 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011366 default:
11367 PyErr_BadArgument();
11368 return NULL;
11369 }
11370 }
11371 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011372 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011373 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011374 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011375 }
11376 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011377 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011378 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011379 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011380}
11381
Alexander Belopolsky40018472011-02-26 01:02:56 +000011382int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011383_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11384{
11385 return unicode_eq(aa, bb);
11386}
11387
11388int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011389PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011390{
Victor Stinner77282cb2013-04-14 19:22:47 +020011391 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011392 const void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011394 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011395
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011396 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020011398 "'in <string>' requires string as left operand, not %.100s",
11399 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011400 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011401 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011402 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011403 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011404 if (ensure_unicode(str) < 0)
11405 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011407 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011408 kind2 = PyUnicode_KIND(substr);
11409 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011410 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011412 len2 = PyUnicode_GET_LENGTH(substr);
11413 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011414 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011415 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011416 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011417 if (len2 == 1) {
11418 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11419 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011420 return result;
11421 }
11422 if (kind2 != kind1) {
Serhiy Storchaka17b47332020-04-01 15:41:49 +030011423 buf2 = unicode_askind(kind2, buf2, len2, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011424 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011425 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011426 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427
Victor Stinner77282cb2013-04-14 19:22:47 +020011428 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011429 case PyUnicode_1BYTE_KIND:
11430 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11431 break;
11432 case PyUnicode_2BYTE_KIND:
11433 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11434 break;
11435 case PyUnicode_4BYTE_KIND:
11436 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11437 break;
11438 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011439 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011440 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011441
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011442 assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
Victor Stinner77282cb2013-04-14 19:22:47 +020011443 if (kind2 != kind1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011444 PyMem_Free((void *)buf2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011445
Guido van Rossum403d68b2000-03-13 15:55:09 +000011446 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011447}
11448
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449/* Concat to string or Unicode object giving a new Unicode object. */
11450
Alexander Belopolsky40018472011-02-26 01:02:56 +000011451PyObject *
11452PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011454 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011455 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011456 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011457
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011458 if (ensure_unicode(left) < 0)
11459 return NULL;
11460
11461 if (!PyUnicode_Check(right)) {
11462 PyErr_Format(PyExc_TypeError,
11463 "can only concatenate str (not \"%.200s\") to str",
Victor Stinner58ac7002020-02-07 03:04:21 +010011464 Py_TYPE(right)->tp_name);
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011465 return NULL;
11466 }
11467 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011468 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469
11470 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011471 if (left == unicode_empty)
11472 return PyUnicode_FromObject(right);
11473 if (right == unicode_empty)
11474 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011476 left_len = PyUnicode_GET_LENGTH(left);
11477 right_len = PyUnicode_GET_LENGTH(right);
11478 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011479 PyErr_SetString(PyExc_OverflowError,
11480 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011481 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011482 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011483 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011484
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011485 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11486 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011487 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011490 result = PyUnicode_New(new_len, maxchar);
11491 if (result == NULL)
11492 return NULL;
11493 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11494 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11495 assert(_PyUnicode_CheckConsistency(result, 1));
11496 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497}
11498
Walter Dörwald1ab83302007-05-18 17:15:44 +000011499void
Victor Stinner23e56682011-10-03 03:54:37 +020011500PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011501{
Victor Stinner23e56682011-10-03 03:54:37 +020011502 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011503 Py_UCS4 maxchar, maxchar2;
11504 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011505
11506 if (p_left == NULL) {
11507 if (!PyErr_Occurred())
11508 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011509 return;
11510 }
Victor Stinner23e56682011-10-03 03:54:37 +020011511 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011512 if (right == NULL || left == NULL
11513 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011514 if (!PyErr_Occurred())
11515 PyErr_BadInternalCall();
11516 goto error;
11517 }
11518
Benjamin Petersonbac79492012-01-14 13:34:47 -050011519 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011520 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011521 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011522 goto error;
11523
Victor Stinner488fa492011-12-12 00:01:39 +010011524 /* Shortcuts */
11525 if (left == unicode_empty) {
11526 Py_DECREF(left);
11527 Py_INCREF(right);
11528 *p_left = right;
11529 return;
11530 }
11531 if (right == unicode_empty)
11532 return;
11533
11534 left_len = PyUnicode_GET_LENGTH(left);
11535 right_len = PyUnicode_GET_LENGTH(right);
11536 if (left_len > PY_SSIZE_T_MAX - right_len) {
11537 PyErr_SetString(PyExc_OverflowError,
11538 "strings are too large to concat");
11539 goto error;
11540 }
11541 new_len = left_len + right_len;
11542
11543 if (unicode_modifiable(left)
11544 && PyUnicode_CheckExact(right)
11545 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011546 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11547 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011548 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011549 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011550 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11551 {
11552 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011553 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011554 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011555
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011556 /* copy 'right' into the newly allocated area of 'left' */
11557 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011558 }
Victor Stinner488fa492011-12-12 00:01:39 +010011559 else {
11560 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11561 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011562 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011563
Victor Stinner488fa492011-12-12 00:01:39 +010011564 /* Concat the two Unicode strings */
11565 res = PyUnicode_New(new_len, maxchar);
11566 if (res == NULL)
11567 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011568 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11569 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011570 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011571 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011572 }
11573 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011574 return;
11575
11576error:
Victor Stinner488fa492011-12-12 00:01:39 +010011577 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011578}
11579
11580void
11581PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11582{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011583 PyUnicode_Append(pleft, right);
11584 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011585}
11586
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011587/*
11588Wraps stringlib_parse_args_finds() and additionally ensures that the
11589first argument is a unicode object.
11590*/
11591
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011592static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011593parse_args_finds_unicode(const char * function_name, PyObject *args,
11594 PyObject **substring,
11595 Py_ssize_t *start, Py_ssize_t *end)
11596{
11597 if(stringlib_parse_args_finds(function_name, args, substring,
11598 start, end)) {
11599 if (ensure_unicode(*substring) < 0)
11600 return 0;
11601 return 1;
11602 }
11603 return 0;
11604}
11605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011606PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011609Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011610string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011611interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612
11613static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011614unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011616 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011617 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011618 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011619 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011620 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011621 const void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011624 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011625 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011627 kind1 = PyUnicode_KIND(self);
11628 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011629 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011630 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 len1 = PyUnicode_GET_LENGTH(self);
11633 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011634 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011635 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011636 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011637
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011638 buf1 = PyUnicode_DATA(self);
11639 buf2 = PyUnicode_DATA(substring);
11640 if (kind2 != kind1) {
Serhiy Storchaka17b47332020-04-01 15:41:49 +030011641 buf2 = unicode_askind(kind2, buf2, len2, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011642 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011643 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011644 }
11645 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011646 case PyUnicode_1BYTE_KIND:
11647 iresult = ucs1lib_count(
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011648 ((const Py_UCS1*)buf1) + start, end - start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649 buf2, len2, PY_SSIZE_T_MAX
11650 );
11651 break;
11652 case PyUnicode_2BYTE_KIND:
11653 iresult = ucs2lib_count(
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011654 ((const Py_UCS2*)buf1) + start, end - start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011655 buf2, len2, PY_SSIZE_T_MAX
11656 );
11657 break;
11658 case PyUnicode_4BYTE_KIND:
11659 iresult = ucs4lib_count(
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011660 ((const Py_UCS4*)buf1) + start, end - start,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011661 buf2, len2, PY_SSIZE_T_MAX
11662 );
11663 break;
11664 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011665 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011666 }
11667
11668 result = PyLong_FromSsize_t(iresult);
11669
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011670 assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substring)));
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011671 if (kind2 != kind1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011672 PyMem_Free((void *)buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011673
Guido van Rossumd57fd912000-03-10 22:53:23 +000011674 return result;
11675}
11676
INADA Naoki3ae20562017-01-16 20:41:20 +090011677/*[clinic input]
11678str.encode as unicode_encode
11679
11680 encoding: str(c_default="NULL") = 'utf-8'
11681 The encoding in which to encode the string.
11682 errors: str(c_default="NULL") = 'strict'
11683 The error handling scheme to use for encoding errors.
11684 The default is 'strict' meaning that encoding errors raise a
11685 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11686 'xmlcharrefreplace' as well as any other name registered with
11687 codecs.register_error that can handle UnicodeEncodeErrors.
11688
11689Encode the string using the codec registered for encoding.
11690[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691
11692static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011693unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011694/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011696 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011697}
11698
INADA Naoki3ae20562017-01-16 20:41:20 +090011699/*[clinic input]
11700str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701
INADA Naoki3ae20562017-01-16 20:41:20 +090011702 tabsize: int = 8
11703
11704Return a copy where all tab characters are expanded using spaces.
11705
11706If tabsize is not given, a tab size of 8 characters is assumed.
11707[clinic start generated code]*/
11708
11709static PyObject *
11710unicode_expandtabs_impl(PyObject *self, int tabsize)
11711/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011713 Py_ssize_t i, j, line_pos, src_len, incr;
11714 Py_UCS4 ch;
11715 PyObject *u;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011716 const void *src_data;
11717 void *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011718 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011719 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720
Antoine Pitrou22425222011-10-04 19:10:51 +020011721 if (PyUnicode_READY(self) == -1)
11722 return NULL;
11723
Thomas Wouters7e474022000-07-16 12:04:32 +000011724 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011725 src_len = PyUnicode_GET_LENGTH(self);
11726 i = j = line_pos = 0;
11727 kind = PyUnicode_KIND(self);
11728 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011729 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011730 for (; i < src_len; i++) {
11731 ch = PyUnicode_READ(kind, src_data, i);
11732 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011733 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011734 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011735 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011736 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011737 goto overflow;
11738 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011739 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011740 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011741 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011743 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011744 goto overflow;
11745 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011747 if (ch == '\n' || ch == '\r')
11748 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011750 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011751 if (!found)
11752 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011753
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011755 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011756 if (!u)
11757 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011758 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759
Antoine Pitroue71d5742011-10-04 15:55:09 +020011760 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761
Antoine Pitroue71d5742011-10-04 15:55:09 +020011762 for (; i < src_len; i++) {
11763 ch = PyUnicode_READ(kind, src_data, i);
11764 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011765 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011766 incr = tabsize - (line_pos % tabsize);
11767 line_pos += incr;
Victor Stinner59423e32018-11-26 13:40:01 +010011768 unicode_fill(kind, dest_data, ' ', j, incr);
Victor Stinnerda79e632012-02-22 13:37:04 +010011769 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011770 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011771 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011772 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011773 line_pos++;
11774 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011775 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011776 if (ch == '\n' || ch == '\r')
11777 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011778 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011779 }
11780 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011781 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011782
Antoine Pitroue71d5742011-10-04 15:55:09 +020011783 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011784 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11785 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786}
11787
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011788PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011789 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790\n\
11791Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011792such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793arguments start and end are interpreted as in slice notation.\n\
11794\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011795Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796
11797static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011799{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011800 /* initialize variables to prevent gcc warning */
11801 PyObject *substring = NULL;
11802 Py_ssize_t start = 0;
11803 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011804 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011806 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011808
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011809 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011812 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011813
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011814 if (result == -2)
11815 return NULL;
11816
Christian Heimes217cfd12007-12-02 14:31:20 +000011817 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011818}
11819
11820static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011821unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822{
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011823 const void *data;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011824 enum PyUnicode_Kind kind;
11825 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011826
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011827 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011828 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011829 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011830 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011831 if (PyUnicode_READY(self) == -1) {
11832 return NULL;
11833 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011834 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11835 PyErr_SetString(PyExc_IndexError, "string index out of range");
11836 return NULL;
11837 }
11838 kind = PyUnicode_KIND(self);
11839 data = PyUnicode_DATA(self);
11840 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011841 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842}
11843
Guido van Rossumc2504932007-09-18 19:42:40 +000011844/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011845 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011846static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011847unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011848{
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011849 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011850
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011851#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011852 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011853#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011854 if (_PyUnicode_HASH(self) != -1)
11855 return _PyUnicode_HASH(self);
11856 if (PyUnicode_READY(self) == -1)
11857 return -1;
animalizea1d14252019-01-02 20:16:06 +080011858
Christian Heimes985ecdc2013-11-20 11:46:18 +010011859 x = _Py_HashBytes(PyUnicode_DATA(self),
11860 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011862 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863}
11864
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011865PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011866 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011867\n\
oldkaa0735f2018-02-02 16:52:55 +080011868Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011869such that sub is contained within S[start:end]. Optional\n\
11870arguments start and end are interpreted as in slice notation.\n\
11871\n\
11872Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873
11874static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011877 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011878 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011879 PyObject *substring = NULL;
11880 Py_ssize_t start = 0;
11881 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011882
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011883 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011886 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011887 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011888
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011889 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011890
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011891 if (result == -2)
11892 return NULL;
11893
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 if (result < 0) {
11895 PyErr_SetString(PyExc_ValueError, "substring not found");
11896 return NULL;
11897 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011898
Christian Heimes217cfd12007-12-02 14:31:20 +000011899 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900}
11901
INADA Naoki3ae20562017-01-16 20:41:20 +090011902/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011903str.isascii as unicode_isascii
11904
11905Return True if all characters in the string are ASCII, False otherwise.
11906
11907ASCII characters have code points in the range U+0000-U+007F.
11908Empty string is ASCII too.
11909[clinic start generated code]*/
11910
11911static PyObject *
11912unicode_isascii_impl(PyObject *self)
11913/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11914{
11915 if (PyUnicode_READY(self) == -1) {
11916 return NULL;
11917 }
11918 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11919}
11920
11921/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011922str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923
INADA Naoki3ae20562017-01-16 20:41:20 +090011924Return True if the string is a lowercase string, False otherwise.
11925
11926A string is lowercase if all cased characters in the string are lowercase and
11927there is at least one cased character in the string.
11928[clinic start generated code]*/
11929
11930static PyObject *
11931unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011932/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011934 Py_ssize_t i, length;
11935 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011936 const void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937 int cased;
11938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011939 if (PyUnicode_READY(self) == -1)
11940 return NULL;
11941 length = PyUnicode_GET_LENGTH(self);
11942 kind = PyUnicode_KIND(self);
11943 data = PyUnicode_DATA(self);
11944
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 if (length == 1)
11947 return PyBool_FromLong(
11948 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011950 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011952 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011953
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011955 for (i = 0; i < length; i++) {
11956 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011957
Benjamin Peterson29060642009-01-31 22:14:21 +000011958 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011959 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011960 else if (!cased && Py_UNICODE_ISLOWER(ch))
11961 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011963 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964}
11965
INADA Naoki3ae20562017-01-16 20:41:20 +090011966/*[clinic input]
11967str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968
INADA Naoki3ae20562017-01-16 20:41:20 +090011969Return True if the string is an uppercase string, False otherwise.
11970
11971A string is uppercase if all cased characters in the string are uppercase and
11972there is at least one cased character in the string.
11973[clinic start generated code]*/
11974
11975static PyObject *
11976unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011977/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 Py_ssize_t i, length;
11980 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030011981 const void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011982 int cased;
11983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011984 if (PyUnicode_READY(self) == -1)
11985 return NULL;
11986 length = PyUnicode_GET_LENGTH(self);
11987 kind = PyUnicode_KIND(self);
11988 data = PyUnicode_DATA(self);
11989
Guido van Rossumd57fd912000-03-10 22:53:23 +000011990 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011991 if (length == 1)
11992 return PyBool_FromLong(
11993 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011995 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011997 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011998
Guido van Rossumd57fd912000-03-10 22:53:23 +000011999 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012000 for (i = 0; i < length; i++) {
12001 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000012002
Benjamin Peterson29060642009-01-31 22:14:21 +000012003 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012004 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000012005 else if (!cased && Py_UNICODE_ISUPPER(ch))
12006 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012008 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009}
12010
INADA Naoki3ae20562017-01-16 20:41:20 +090012011/*[clinic input]
12012str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013
INADA Naoki3ae20562017-01-16 20:41:20 +090012014Return True if the string is a title-cased string, False otherwise.
12015
12016In a title-cased string, upper- and title-case characters may only
12017follow uncased characters and lowercase characters only cased ones.
12018[clinic start generated code]*/
12019
12020static PyObject *
12021unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012022/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012023{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 Py_ssize_t i, length;
12025 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012026 const void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012027 int cased, previous_is_cased;
12028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 if (PyUnicode_READY(self) == -1)
12030 return NULL;
12031 length = PyUnicode_GET_LENGTH(self);
12032 kind = PyUnicode_KIND(self);
12033 data = PyUnicode_DATA(self);
12034
Guido van Rossumd57fd912000-03-10 22:53:23 +000012035 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 if (length == 1) {
12037 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12038 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
12039 (Py_UNICODE_ISUPPER(ch) != 0));
12040 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012041
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012042 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012044 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012045
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046 cased = 0;
12047 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012048 for (i = 0; i < length; i++) {
12049 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000012050
Benjamin Peterson29060642009-01-31 22:14:21 +000012051 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
12052 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012053 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000012054 previous_is_cased = 1;
12055 cased = 1;
12056 }
12057 else if (Py_UNICODE_ISLOWER(ch)) {
12058 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012059 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000012060 previous_is_cased = 1;
12061 cased = 1;
12062 }
12063 else
12064 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012065 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000012066 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067}
12068
INADA Naoki3ae20562017-01-16 20:41:20 +090012069/*[clinic input]
12070str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012071
INADA Naoki3ae20562017-01-16 20:41:20 +090012072Return True if the string is a whitespace string, False otherwise.
12073
12074A string is whitespace if all characters in the string are whitespace and there
12075is at least one character in the string.
12076[clinic start generated code]*/
12077
12078static PyObject *
12079unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012080/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
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;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012084 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085
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_ISSPACE(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 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012103 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012104 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012106 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012107}
12108
INADA Naoki3ae20562017-01-16 20:41:20 +090012109/*[clinic input]
12110str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012111
INADA Naoki3ae20562017-01-16 20:41:20 +090012112Return True if the string is an alphabetic string, False otherwise.
12113
12114A string is alphabetic if all characters in the string are alphabetic and there
12115is at least one character in the string.
12116[clinic start generated code]*/
12117
12118static PyObject *
12119unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012120/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012121{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012122 Py_ssize_t i, length;
12123 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012124 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125
12126 if (PyUnicode_READY(self) == -1)
12127 return NULL;
12128 length = PyUnicode_GET_LENGTH(self);
12129 kind = PyUnicode_KIND(self);
12130 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012131
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012132 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012133 if (length == 1)
12134 return PyBool_FromLong(
12135 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012136
12137 /* 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é Lemburga7acf422000-07-05 09:49:44 +000012140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012141 for (i = 0; i < length; i++) {
12142 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012143 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012144 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012145 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012146}
12147
INADA Naoki3ae20562017-01-16 20:41:20 +090012148/*[clinic input]
12149str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012150
INADA Naoki3ae20562017-01-16 20:41:20 +090012151Return True if the string is an alpha-numeric string, False otherwise.
12152
12153A string is alpha-numeric if all characters in the string are alpha-numeric and
12154there is at least one character in the string.
12155[clinic start generated code]*/
12156
12157static PyObject *
12158unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012159/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012160{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012161 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012162 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163 Py_ssize_t len, i;
12164
12165 if (PyUnicode_READY(self) == -1)
12166 return NULL;
12167
12168 kind = PyUnicode_KIND(self);
12169 data = PyUnicode_DATA(self);
12170 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012171
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012172 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173 if (len == 1) {
12174 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12175 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12176 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012177
12178 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012179 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012180 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012182 for (i = 0; i < len; i++) {
12183 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012184 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012185 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012186 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012187 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012188}
12189
INADA Naoki3ae20562017-01-16 20:41:20 +090012190/*[clinic input]
12191str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192
INADA Naoki3ae20562017-01-16 20:41:20 +090012193Return True if the string is a decimal string, False otherwise.
12194
12195A string is a decimal string if all characters in the string are decimal and
12196there is at least one character in the string.
12197[clinic start generated code]*/
12198
12199static PyObject *
12200unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012201/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 Py_ssize_t i, length;
12204 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012205 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012206
12207 if (PyUnicode_READY(self) == -1)
12208 return NULL;
12209 length = PyUnicode_GET_LENGTH(self);
12210 kind = PyUnicode_KIND(self);
12211 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212
Guido van Rossumd57fd912000-03-10 22:53:23 +000012213 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012214 if (length == 1)
12215 return PyBool_FromLong(
12216 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012218 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012219 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012220 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012221
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 for (i = 0; i < length; i++) {
12223 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012224 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012225 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012226 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227}
12228
INADA Naoki3ae20562017-01-16 20:41:20 +090012229/*[clinic input]
12230str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231
INADA Naoki3ae20562017-01-16 20:41:20 +090012232Return True if the string is a digit string, False otherwise.
12233
12234A string is a digit string if all characters in the string are digits and there
12235is at least one character in the string.
12236[clinic start generated code]*/
12237
12238static PyObject *
12239unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012240/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012242 Py_ssize_t i, length;
12243 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012244 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012245
12246 if (PyUnicode_READY(self) == -1)
12247 return NULL;
12248 length = PyUnicode_GET_LENGTH(self);
12249 kind = PyUnicode_KIND(self);
12250 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253 if (length == 1) {
12254 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12255 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12256 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012258 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012259 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012260 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262 for (i = 0; i < length; i++) {
12263 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012264 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012266 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267}
12268
INADA Naoki3ae20562017-01-16 20:41:20 +090012269/*[clinic input]
12270str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271
INADA Naoki3ae20562017-01-16 20:41:20 +090012272Return True if the string is a numeric string, False otherwise.
12273
12274A string is numeric if all characters in the string are numeric and there is at
12275least one character in the string.
12276[clinic start generated code]*/
12277
12278static PyObject *
12279unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012280/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012282 Py_ssize_t i, length;
12283 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012284 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285
12286 if (PyUnicode_READY(self) == -1)
12287 return NULL;
12288 length = PyUnicode_GET_LENGTH(self);
12289 kind = PyUnicode_KIND(self);
12290 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012293 if (length == 1)
12294 return PyBool_FromLong(
12295 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012297 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012299 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 for (i = 0; i < length; i++) {
12302 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012303 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012304 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012305 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306}
12307
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012308Py_ssize_t
12309_PyUnicode_ScanIdentifier(PyObject *self)
Martin v. Löwis47383402007-08-15 07:32:56 +000012310{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 Py_ssize_t i;
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012312 if (PyUnicode_READY(self) == -1)
12313 return -1;
Martin v. Löwis47383402007-08-15 07:32:56 +000012314
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012315 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
Victor Stinnerf3e7ea52020-02-11 14:29:33 +010012316 if (len == 0) {
12317 /* an empty string is not a valid identifier */
Benjamin Peterson29060642009-01-31 22:14:21 +000012318 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012319 }
12320
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012321 int kind = PyUnicode_KIND(self);
12322 const void *data = PyUnicode_DATA(self);
12323 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Martin v. Löwis47383402007-08-15 07:32:56 +000012324 /* PEP 3131 says that the first character must be in
12325 XID_Start and subsequent characters in XID_Continue,
12326 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012327 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012328 letters, digits, underscore). However, given the current
12329 definition of XID_Start and XID_Continue, it is sufficient
12330 to check just for these, except that _ must be allowed
12331 as starting an identifier. */
Victor Stinnerf3e7ea52020-02-11 14:29:33 +010012332 if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
Martin v. Löwis47383402007-08-15 07:32:56 +000012333 return 0;
Victor Stinnerf3e7ea52020-02-11 14:29:33 +010012334 }
Martin v. Löwis47383402007-08-15 07:32:56 +000012335
Victor Stinnerf3e7ea52020-02-11 14:29:33 +010012336 for (i = 1; i < len; i++) {
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012337 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerf3e7ea52020-02-11 14:29:33 +010012338 if (!_PyUnicode_IsXidContinue(ch)) {
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012339 return i;
Victor Stinnerf3e7ea52020-02-11 14:29:33 +010012340 }
12341 }
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012342 return i;
12343}
12344
12345int
12346PyUnicode_IsIdentifier(PyObject *self)
12347{
12348 if (PyUnicode_IS_READY(self)) {
12349 Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
12350 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
12351 /* an empty string is not a valid identifier */
12352 return len && i == len;
12353 }
12354 else {
Serhiy Storchaka5650e762020-05-12 16:18:00 +030012355 Py_ssize_t i = 0, len = PyUnicode_GET_SIZE(self);
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012356 if (len == 0) {
12357 /* an empty string is not a valid identifier */
12358 return 0;
12359 }
12360
12361 const wchar_t *wstr = _PyUnicode_WSTR(self);
Serhiy Storchaka5650e762020-05-12 16:18:00 +030012362 Py_UCS4 ch = wstr[i++];
12363#if SIZEOF_WCHAR_T == 2
12364 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
12365 && i < len
12366 && Py_UNICODE_IS_LOW_SURROGATE(wstr[i]))
12367 {
12368 ch = Py_UNICODE_JOIN_SURROGATES(ch, wstr[i]);
12369 i++;
12370 }
12371#endif
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012372 if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
12373 return 0;
12374 }
12375
Serhiy Storchaka5650e762020-05-12 16:18:00 +030012376 while (i < len) {
12377 ch = wstr[i++];
12378#if SIZEOF_WCHAR_T == 2
12379 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
12380 && i < len
12381 && Py_UNICODE_IS_LOW_SURROGATE(wstr[i]))
12382 {
12383 ch = Py_UNICODE_JOIN_SURROGATES(ch, wstr[i]);
12384 i++;
12385 }
12386#endif
Serhiy Storchaka74ea6b52020-05-12 12:42:04 +030012387 if (!_PyUnicode_IsXidContinue(ch)) {
12388 return 0;
12389 }
12390 }
12391 return 1;
12392 }
Martin v. Löwis47383402007-08-15 07:32:56 +000012393}
12394
INADA Naoki3ae20562017-01-16 20:41:20 +090012395/*[clinic input]
12396str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012397
INADA Naoki3ae20562017-01-16 20:41:20 +090012398Return True if the string is a valid Python identifier, False otherwise.
12399
Sanyam Khuranaffc5a142018-10-08 12:23:32 +053012400Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012401such as "def" or "class".
INADA Naoki3ae20562017-01-16 20:41:20 +090012402[clinic start generated code]*/
12403
12404static PyObject *
12405unicode_isidentifier_impl(PyObject *self)
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012406/*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012407{
12408 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12409}
12410
INADA Naoki3ae20562017-01-16 20:41:20 +090012411/*[clinic input]
12412str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012413
INADA Naoki3ae20562017-01-16 20:41:20 +090012414Return True if the string is printable, False otherwise.
12415
12416A string is printable if all of its characters are considered printable in
12417repr() or if it is empty.
12418[clinic start generated code]*/
12419
12420static PyObject *
12421unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012422/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012423{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 Py_ssize_t i, length;
12425 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012426 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012427
12428 if (PyUnicode_READY(self) == -1)
12429 return NULL;
12430 length = PyUnicode_GET_LENGTH(self);
12431 kind = PyUnicode_KIND(self);
12432 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012433
12434 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012435 if (length == 1)
12436 return PyBool_FromLong(
12437 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012438
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012439 for (i = 0; i < length; i++) {
12440 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012441 Py_RETURN_FALSE;
12442 }
12443 }
12444 Py_RETURN_TRUE;
12445}
12446
INADA Naoki3ae20562017-01-16 20:41:20 +090012447/*[clinic input]
12448str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012449
INADA Naoki3ae20562017-01-16 20:41:20 +090012450 iterable: object
12451 /
12452
12453Concatenate any number of strings.
12454
Martin Panter91a88662017-01-24 00:30:06 +000012455The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012456The result is returned as a new string.
12457
12458Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12459[clinic start generated code]*/
12460
12461static PyObject *
12462unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012463/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012464{
INADA Naoki3ae20562017-01-16 20:41:20 +090012465 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012466}
12467
Martin v. Löwis18e16552006-02-15 17:27:45 +000012468static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012469unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012470{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012471 if (PyUnicode_READY(self) == -1)
12472 return -1;
12473 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012474}
12475
INADA Naoki3ae20562017-01-16 20:41:20 +090012476/*[clinic input]
12477str.ljust as unicode_ljust
12478
12479 width: Py_ssize_t
12480 fillchar: Py_UCS4 = ' '
12481 /
12482
12483Return a left-justified string of length width.
12484
12485Padding is done using the specified fill character (default is a space).
12486[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012487
12488static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012489unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12490/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012491{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012492 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012493 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012494
Victor Stinnerc4b49542011-12-11 22:44:26 +010012495 if (PyUnicode_GET_LENGTH(self) >= width)
12496 return unicode_result_unchanged(self);
12497
12498 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499}
12500
INADA Naoki3ae20562017-01-16 20:41:20 +090012501/*[clinic input]
12502str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503
INADA Naoki3ae20562017-01-16 20:41:20 +090012504Return a copy of the string converted to lowercase.
12505[clinic start generated code]*/
12506
12507static PyObject *
12508unicode_lower_impl(PyObject *self)
12509/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012511 if (PyUnicode_READY(self) == -1)
12512 return NULL;
12513 if (PyUnicode_IS_ASCII(self))
12514 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012515 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516}
12517
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012518#define LEFTSTRIP 0
12519#define RIGHTSTRIP 1
12520#define BOTHSTRIP 2
12521
12522/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012523static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012524
INADA Naoki3ae20562017-01-16 20:41:20 +090012525#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012526
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012527/* externally visible for str.strip(unicode) */
12528PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012529_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012530{
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012531 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012532 int kind;
12533 Py_ssize_t i, j, len;
12534 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012535 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12538 return NULL;
12539
12540 kind = PyUnicode_KIND(self);
12541 data = PyUnicode_DATA(self);
12542 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012543 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12545 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012546 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012547
Benjamin Peterson14339b62009-01-31 16:36:08 +000012548 i = 0;
12549 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012550 while (i < len) {
12551 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12552 if (!BLOOM(sepmask, ch))
12553 break;
12554 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12555 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012556 i++;
12557 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012558 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012559
Benjamin Peterson14339b62009-01-31 16:36:08 +000012560 j = len;
12561 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012562 j--;
12563 while (j >= i) {
12564 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12565 if (!BLOOM(sepmask, ch))
12566 break;
12567 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12568 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012569 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012570 }
12571
Benjamin Peterson29060642009-01-31 22:14:21 +000012572 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012573 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012574
Victor Stinner7931d9a2011-11-04 00:22:48 +010012575 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576}
12577
12578PyObject*
12579PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12580{
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012581 const unsigned char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012583 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584
Victor Stinnerde636f32011-10-01 03:55:54 +020012585 if (PyUnicode_READY(self) == -1)
12586 return NULL;
12587
Victor Stinner684d5fd2012-05-03 02:32:34 +020012588 length = PyUnicode_GET_LENGTH(self);
12589 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012590
Victor Stinner684d5fd2012-05-03 02:32:34 +020012591 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012592 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593
Victor Stinnerde636f32011-10-01 03:55:54 +020012594 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012595 PyErr_SetString(PyExc_IndexError, "string index out of range");
12596 return NULL;
12597 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012598 if (start >= length || end < start)
12599 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012600
Victor Stinner684d5fd2012-05-03 02:32:34 +020012601 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012602 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012603 data = PyUnicode_1BYTE_DATA(self);
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012604 return _PyUnicode_FromASCII((const char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012605 }
12606 else {
12607 kind = PyUnicode_KIND(self);
12608 data = PyUnicode_1BYTE_DATA(self);
12609 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012610 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012611 length);
12612 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614
12615static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012616do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012618 Py_ssize_t len, i, j;
12619
12620 if (PyUnicode_READY(self) == -1)
12621 return NULL;
12622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012624
Victor Stinnercc7af722013-04-09 22:39:24 +020012625 if (PyUnicode_IS_ASCII(self)) {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012626 const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
Victor Stinnercc7af722013-04-09 22:39:24 +020012627
12628 i = 0;
12629 if (striptype != RIGHTSTRIP) {
12630 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012631 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012632 if (!_Py_ascii_whitespace[ch])
12633 break;
12634 i++;
12635 }
12636 }
12637
12638 j = len;
12639 if (striptype != LEFTSTRIP) {
12640 j--;
12641 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012642 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012643 if (!_Py_ascii_whitespace[ch])
12644 break;
12645 j--;
12646 }
12647 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012648 }
12649 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012650 else {
12651 int kind = PyUnicode_KIND(self);
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012652 const void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012653
Victor Stinnercc7af722013-04-09 22:39:24 +020012654 i = 0;
12655 if (striptype != RIGHTSTRIP) {
12656 while (i < len) {
12657 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12658 if (!Py_UNICODE_ISSPACE(ch))
12659 break;
12660 i++;
12661 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012662 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012663
12664 j = len;
12665 if (striptype != LEFTSTRIP) {
12666 j--;
12667 while (j >= i) {
12668 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12669 if (!Py_UNICODE_ISSPACE(ch))
12670 break;
12671 j--;
12672 }
12673 j++;
12674 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012675 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012676
Victor Stinner7931d9a2011-11-04 00:22:48 +010012677 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012678}
12679
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012680
12681static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012682do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012683{
Serhiy Storchaka279f4462019-09-14 12:24:05 +030012684 if (sep != Py_None) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012685 if (PyUnicode_Check(sep))
12686 return _PyUnicode_XStrip(self, striptype, sep);
12687 else {
12688 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012689 "%s arg must be None or str",
12690 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012691 return NULL;
12692 }
12693 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012694
Benjamin Peterson14339b62009-01-31 16:36:08 +000012695 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012696}
12697
12698
INADA Naoki3ae20562017-01-16 20:41:20 +090012699/*[clinic input]
12700str.strip as unicode_strip
12701
12702 chars: object = None
12703 /
12704
Zachary Ware09895c22019-10-09 16:09:00 -050012705Return a copy of the string with leading and trailing whitespace removed.
INADA Naoki3ae20562017-01-16 20:41:20 +090012706
12707If chars is given and not None, remove characters in chars instead.
12708[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012709
12710static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012711unicode_strip_impl(PyObject *self, PyObject *chars)
Zachary Ware09895c22019-10-09 16:09:00 -050012712/*[clinic end generated code: output=ca19018454345d57 input=385289c6f423b954]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012713{
INADA Naoki3ae20562017-01-16 20:41:20 +090012714 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012715}
12716
12717
INADA Naoki3ae20562017-01-16 20:41:20 +090012718/*[clinic input]
12719str.lstrip as unicode_lstrip
12720
Serhiy Storchaka279f4462019-09-14 12:24:05 +030012721 chars: object = None
INADA Naoki3ae20562017-01-16 20:41:20 +090012722 /
12723
12724Return a copy of the string with leading whitespace removed.
12725
12726If chars is given and not None, remove characters in chars instead.
12727[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012728
12729static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012730unicode_lstrip_impl(PyObject *self, PyObject *chars)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030012731/*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012732{
INADA Naoki3ae20562017-01-16 20:41:20 +090012733 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012734}
12735
12736
INADA Naoki3ae20562017-01-16 20:41:20 +090012737/*[clinic input]
12738str.rstrip as unicode_rstrip
12739
Serhiy Storchaka279f4462019-09-14 12:24:05 +030012740 chars: object = None
INADA Naoki3ae20562017-01-16 20:41:20 +090012741 /
12742
12743Return a copy of the string with trailing whitespace removed.
12744
12745If chars is given and not None, remove characters in chars instead.
12746[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012747
12748static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012749unicode_rstrip_impl(PyObject *self, PyObject *chars)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030012750/*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012751{
INADA Naoki3ae20562017-01-16 20:41:20 +090012752 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012753}
12754
12755
Guido van Rossumd57fd912000-03-10 22:53:23 +000012756static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012757unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012759 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012760 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761
Serhiy Storchaka05997252013-01-26 12:14:02 +020012762 if (len < 1)
12763 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764
Victor Stinnerc4b49542011-12-11 22:44:26 +010012765 /* no repeat, return original string */
12766 if (len == 1)
12767 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012768
Benjamin Petersonbac79492012-01-14 13:34:47 -050012769 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012770 return NULL;
12771
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012772 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012773 PyErr_SetString(PyExc_OverflowError,
12774 "repeated string is too long");
12775 return NULL;
12776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012777 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012778
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012779 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780 if (!u)
12781 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012782 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784 if (PyUnicode_GET_LENGTH(str) == 1) {
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012785 int kind = PyUnicode_KIND(str);
12786 Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012787 if (kind == PyUnicode_1BYTE_KIND) {
12788 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012789 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012790 }
12791 else if (kind == PyUnicode_2BYTE_KIND) {
12792 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012793 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012794 ucs2[n] = fill_char;
12795 } else {
12796 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12797 assert(kind == PyUnicode_4BYTE_KIND);
12798 for (n = 0; n < len; ++n)
12799 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012800 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012801 }
12802 else {
12803 /* number of characters copied this far */
12804 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012805 Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012806 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012807 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012809 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012811 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012812 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012813 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814 }
12815
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012816 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012817 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818}
12819
Alexander Belopolsky40018472011-02-26 01:02:56 +000012820PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012821PyUnicode_Replace(PyObject *str,
12822 PyObject *substr,
12823 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012824 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012826 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12827 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012828 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012829 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830}
12831
INADA Naoki3ae20562017-01-16 20:41:20 +090012832/*[clinic input]
12833str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834
INADA Naoki3ae20562017-01-16 20:41:20 +090012835 old: unicode
12836 new: unicode
12837 count: Py_ssize_t = -1
12838 Maximum number of occurrences to replace.
12839 -1 (the default value) means replace all occurrences.
12840 /
12841
12842Return a copy with all occurrences of substring old replaced by new.
12843
12844If the optional argument count is given, only the first count occurrences are
12845replaced.
12846[clinic start generated code]*/
12847
12848static PyObject *
12849unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12850 Py_ssize_t count)
12851/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012852{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012853 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012854 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012855 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012856}
12857
sweeneydea81849b2020-04-22 17:05:48 -040012858/*[clinic input]
12859str.removeprefix as unicode_removeprefix
12860
12861 prefix: unicode
12862 /
12863
12864Return a str with the given prefix string removed if present.
12865
12866If the string starts with the prefix string, return string[len(prefix):].
12867Otherwise, return a copy of the original string.
12868[clinic start generated code]*/
12869
12870static PyObject *
12871unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
12872/*[clinic end generated code: output=f1e5945e9763bcb9 input=27ec40b99a37eb88]*/
12873{
12874 int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
12875 if (match == -1) {
12876 return NULL;
12877 }
12878 if (match) {
12879 return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
12880 PyUnicode_GET_LENGTH(self));
12881 }
12882 return unicode_result_unchanged(self);
12883}
12884
12885/*[clinic input]
12886str.removesuffix as unicode_removesuffix
12887
12888 suffix: unicode
12889 /
12890
12891Return a str with the given suffix string removed if present.
12892
12893If the string ends with the suffix string and that suffix is not empty,
12894return string[:-len(suffix)]. Otherwise, return a copy of the original
12895string.
12896[clinic start generated code]*/
12897
12898static PyObject *
12899unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
12900/*[clinic end generated code: output=d36629e227636822 input=12cc32561e769be4]*/
12901{
12902 int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
12903 if (match == -1) {
12904 return NULL;
12905 }
12906 if (match) {
12907 return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
12908 - PyUnicode_GET_LENGTH(suffix));
12909 }
12910 return unicode_result_unchanged(self);
12911}
12912
Alexander Belopolsky40018472011-02-26 01:02:56 +000012913static PyObject *
12914unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012915{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012916 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012917 Py_ssize_t isize;
12918 Py_ssize_t osize, squote, dquote, i, o;
12919 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012920 int ikind, okind, unchanged;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030012921 const void *idata;
12922 void *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012924 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012925 return NULL;
12926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012927 isize = PyUnicode_GET_LENGTH(unicode);
12928 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012929
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012930 /* Compute length of output, quote characters, and
12931 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012932 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012933 max = 127;
12934 squote = dquote = 0;
12935 ikind = PyUnicode_KIND(unicode);
12936 for (i = 0; i < isize; i++) {
12937 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012938 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012939 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012940 case '\'': squote++; break;
12941 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012942 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012943 incr = 2;
12944 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012945 default:
12946 /* Fast-path ASCII */
12947 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012948 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012949 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012950 ;
12951 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012952 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012953 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012954 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012955 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012956 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012957 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012958 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012959 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012960 if (osize > PY_SSIZE_T_MAX - incr) {
12961 PyErr_SetString(PyExc_OverflowError,
12962 "string is too long to generate repr");
12963 return NULL;
12964 }
12965 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012966 }
12967
12968 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012969 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012970 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012971 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012972 if (dquote)
12973 /* Both squote and dquote present. Use squote,
12974 and escape them */
12975 osize += squote;
12976 else
12977 quote = '"';
12978 }
Victor Stinner55c08782013-04-14 18:45:39 +020012979 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980
12981 repr = PyUnicode_New(osize, max);
12982 if (repr == NULL)
12983 return NULL;
12984 okind = PyUnicode_KIND(repr);
12985 odata = PyUnicode_DATA(repr);
12986
12987 PyUnicode_WRITE(okind, odata, 0, quote);
12988 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012989 if (unchanged) {
12990 _PyUnicode_FastCopyCharacters(repr, 1,
12991 unicode, 0,
12992 isize);
12993 }
12994 else {
12995 for (i = 0, o = 1; i < isize; i++) {
12996 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997
Victor Stinner55c08782013-04-14 18:45:39 +020012998 /* Escape quotes and backslashes */
12999 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000013000 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013001 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020013002 continue;
13003 }
13004
13005 /* Map special whitespace to '\t', \n', '\r' */
13006 if (ch == '\t') {
13007 PyUnicode_WRITE(okind, odata, o++, '\\');
13008 PyUnicode_WRITE(okind, odata, o++, 't');
13009 }
13010 else if (ch == '\n') {
13011 PyUnicode_WRITE(okind, odata, o++, '\\');
13012 PyUnicode_WRITE(okind, odata, o++, 'n');
13013 }
13014 else if (ch == '\r') {
13015 PyUnicode_WRITE(okind, odata, o++, '\\');
13016 PyUnicode_WRITE(okind, odata, o++, 'r');
13017 }
13018
13019 /* Map non-printable US ASCII to '\xhh' */
13020 else if (ch < ' ' || ch == 0x7F) {
13021 PyUnicode_WRITE(okind, odata, o++, '\\');
13022 PyUnicode_WRITE(okind, odata, o++, 'x');
13023 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
13024 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
13025 }
13026
13027 /* Copy ASCII characters as-is */
13028 else if (ch < 0x7F) {
13029 PyUnicode_WRITE(okind, odata, o++, ch);
13030 }
13031
13032 /* Non-ASCII characters */
13033 else {
13034 /* Map Unicode whitespace and control characters
13035 (categories Z* and C* except ASCII space)
13036 */
13037 if (!Py_UNICODE_ISPRINTABLE(ch)) {
13038 PyUnicode_WRITE(okind, odata, o++, '\\');
13039 /* Map 8-bit characters to '\xhh' */
13040 if (ch <= 0xff) {
13041 PyUnicode_WRITE(okind, odata, o++, 'x');
13042 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
13043 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
13044 }
13045 /* Map 16-bit characters to '\uxxxx' */
13046 else if (ch <= 0xffff) {
13047 PyUnicode_WRITE(okind, odata, o++, 'u');
13048 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
13049 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
13050 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
13051 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
13052 }
13053 /* Map 21-bit characters to '\U00xxxxxx' */
13054 else {
13055 PyUnicode_WRITE(okind, odata, o++, 'U');
13056 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
13057 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
13058 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
13059 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
13060 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
13061 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
13062 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
13063 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
13064 }
13065 }
13066 /* Copy characters as-is */
13067 else {
13068 PyUnicode_WRITE(okind, odata, o++, ch);
13069 }
Georg Brandl559e5d72008-06-11 18:37:52 +000013070 }
13071 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000013072 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013073 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020013074 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000013075 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013076}
13077
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013078PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013079 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013080\n\
13081Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080013082such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013083arguments start and end are interpreted as in slice notation.\n\
13084\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013085Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013086
13087static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013088unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013089{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010013090 /* initialize variables to prevent gcc warning */
13091 PyObject *substring = NULL;
13092 Py_ssize_t start = 0;
13093 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013094 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030013096 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013097 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013098
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013099 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013100 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013102 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 if (result == -2)
13105 return NULL;
13106
Christian Heimes217cfd12007-12-02 14:31:20 +000013107 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108}
13109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013110PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013111 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013112\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070013113Return the highest index in S where substring sub is found,\n\
13114such that sub is contained within S[start:end]. Optional\n\
13115arguments start and end are interpreted as in slice notation.\n\
13116\n\
13117Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013118
13119static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013120unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010013122 /* initialize variables to prevent gcc warning */
13123 PyObject *substring = NULL;
13124 Py_ssize_t start = 0;
13125 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013126 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013127
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030013128 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013129 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013131 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013132 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013133
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013134 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013136 if (result == -2)
13137 return NULL;
13138
Guido van Rossumd57fd912000-03-10 22:53:23 +000013139 if (result < 0) {
13140 PyErr_SetString(PyExc_ValueError, "substring not found");
13141 return NULL;
13142 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013143
Christian Heimes217cfd12007-12-02 14:31:20 +000013144 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013145}
13146
INADA Naoki3ae20562017-01-16 20:41:20 +090013147/*[clinic input]
13148str.rjust as unicode_rjust
13149
13150 width: Py_ssize_t
13151 fillchar: Py_UCS4 = ' '
13152 /
13153
13154Return a right-justified string of length width.
13155
13156Padding is done using the specified fill character (default is a space).
13157[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158
13159static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013160unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
13161/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013162{
Benjamin Petersonbac79492012-01-14 13:34:47 -050013163 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164 return NULL;
13165
Victor Stinnerc4b49542011-12-11 22:44:26 +010013166 if (PyUnicode_GET_LENGTH(self) >= width)
13167 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168
Victor Stinnerc4b49542011-12-11 22:44:26 +010013169 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013170}
13171
Alexander Belopolsky40018472011-02-26 01:02:56 +000013172PyObject *
13173PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013174{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013175 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013176 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013178 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013179}
13180
INADA Naoki3ae20562017-01-16 20:41:20 +090013181/*[clinic input]
13182str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183
INADA Naoki3ae20562017-01-16 20:41:20 +090013184 sep: object = None
13185 The delimiter according which to split the string.
13186 None (the default value) means split according to any whitespace,
13187 and discard empty strings from the result.
13188 maxsplit: Py_ssize_t = -1
13189 Maximum number of splits to do.
13190 -1 (the default value) means no limit.
13191
13192Return a list of the words in the string, using sep as the delimiter string.
13193[clinic start generated code]*/
13194
13195static PyObject *
13196unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13197/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198{
INADA Naoki3ae20562017-01-16 20:41:20 +090013199 if (sep == Py_None)
13200 return split(self, NULL, maxsplit);
13201 if (PyUnicode_Check(sep))
13202 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013203
Victor Stinner998b8062018-09-12 00:23:25 +020013204 PyErr_Format(PyExc_TypeError,
13205 "must be str or None, not %.100s",
13206 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013207 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208}
13209
Thomas Wouters477c8d52006-05-27 19:21:47 +000013210PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013211PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013212{
Thomas Wouters477c8d52006-05-27 19:21:47 +000013213 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013214 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013215 const void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013216 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013217
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013218 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013219 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013220
Victor Stinner14f8f022011-10-05 20:58:25 +020013221 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013222 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013223 len1 = PyUnicode_GET_LENGTH(str_obj);
13224 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013225 if (kind1 < kind2 || len1 < len2) {
13226 _Py_INCREF_UNICODE_EMPTY();
13227 if (!unicode_empty)
13228 out = NULL;
13229 else {
13230 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
13231 Py_DECREF(unicode_empty);
13232 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013233 return out;
13234 }
13235 buf1 = PyUnicode_DATA(str_obj);
13236 buf2 = PyUnicode_DATA(sep_obj);
13237 if (kind2 != kind1) {
Serhiy Storchaka17b47332020-04-01 15:41:49 +030013238 buf2 = unicode_askind(kind2, buf2, len2, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013239 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013240 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013241 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013242
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013243 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013244 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013245 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13246 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13247 else
13248 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013249 break;
13250 case PyUnicode_2BYTE_KIND:
13251 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13252 break;
13253 case PyUnicode_4BYTE_KIND:
13254 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
13255 break;
13256 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013257 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013258 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013259
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013260 assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013261 if (kind2 != kind1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013262 PyMem_Free((void *)buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013263
13264 return out;
13265}
13266
13267
13268PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013269PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000013270{
Thomas Wouters477c8d52006-05-27 19:21:47 +000013271 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013272 int kind1, kind2;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013273 const void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013274 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013275
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013276 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013277 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000013278
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013279 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013280 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013281 len1 = PyUnicode_GET_LENGTH(str_obj);
13282 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013283 if (kind1 < kind2 || len1 < len2) {
13284 _Py_INCREF_UNICODE_EMPTY();
13285 if (!unicode_empty)
13286 out = NULL;
13287 else {
13288 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
13289 Py_DECREF(unicode_empty);
13290 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013291 return out;
13292 }
13293 buf1 = PyUnicode_DATA(str_obj);
13294 buf2 = PyUnicode_DATA(sep_obj);
13295 if (kind2 != kind1) {
Serhiy Storchaka17b47332020-04-01 15:41:49 +030013296 buf2 = unicode_askind(kind2, buf2, len2, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013297 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013298 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013300
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013301 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013302 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013303 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13304 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13305 else
13306 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013307 break;
13308 case PyUnicode_2BYTE_KIND:
13309 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13310 break;
13311 case PyUnicode_4BYTE_KIND:
13312 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13313 break;
13314 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013315 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013316 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013317
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013318 assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013319 if (kind2 != kind1)
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013320 PyMem_Free((void *)buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013321
13322 return out;
13323}
13324
INADA Naoki3ae20562017-01-16 20:41:20 +090013325/*[clinic input]
13326str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013327
INADA Naoki3ae20562017-01-16 20:41:20 +090013328 sep: object
13329 /
13330
13331Partition the string into three parts using the given separator.
13332
13333This will search for the separator in the string. If the separator is found,
13334returns a 3-tuple containing the part before the separator, the separator
13335itself, and the part after it.
13336
13337If the separator is not found, returns a 3-tuple containing the original string
13338and two empty strings.
13339[clinic start generated code]*/
13340
13341static PyObject *
13342unicode_partition(PyObject *self, PyObject *sep)
13343/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013344{
INADA Naoki3ae20562017-01-16 20:41:20 +090013345 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013346}
13347
INADA Naoki3ae20562017-01-16 20:41:20 +090013348/*[clinic input]
13349str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013350
INADA Naoki3ae20562017-01-16 20:41:20 +090013351Partition the string into three parts using the given separator.
13352
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013353This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090013354the separator is found, returns a 3-tuple containing the part before the
13355separator, the separator itself, and the part after it.
13356
13357If the separator is not found, returns a 3-tuple containing two empty strings
13358and the original string.
13359[clinic start generated code]*/
13360
13361static PyObject *
13362unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013363/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013364{
INADA Naoki3ae20562017-01-16 20:41:20 +090013365 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013366}
13367
Alexander Belopolsky40018472011-02-26 01:02:56 +000013368PyObject *
13369PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013370{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013371 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013372 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013373
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013374 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013375}
13376
INADA Naoki3ae20562017-01-16 20:41:20 +090013377/*[clinic input]
13378str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013379
INADA Naoki3ae20562017-01-16 20:41:20 +090013380Return a list of the words in the string, using sep as the delimiter string.
13381
13382Splits are done starting at the end of the string and working to the front.
13383[clinic start generated code]*/
13384
13385static PyObject *
13386unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13387/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013388{
INADA Naoki3ae20562017-01-16 20:41:20 +090013389 if (sep == Py_None)
13390 return rsplit(self, NULL, maxsplit);
13391 if (PyUnicode_Check(sep))
13392 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013393
Victor Stinner998b8062018-09-12 00:23:25 +020013394 PyErr_Format(PyExc_TypeError,
13395 "must be str or None, not %.100s",
13396 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013397 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013398}
13399
INADA Naoki3ae20562017-01-16 20:41:20 +090013400/*[clinic input]
13401str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013403 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013404
13405Return a list of the lines in the string, breaking at line boundaries.
13406
13407Line breaks are not included in the resulting list unless keepends is given and
13408true.
13409[clinic start generated code]*/
13410
13411static PyObject *
13412unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013413/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013414{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013415 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013416}
13417
13418static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013419PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013420{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013421 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013422}
13423
INADA Naoki3ae20562017-01-16 20:41:20 +090013424/*[clinic input]
13425str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013426
INADA Naoki3ae20562017-01-16 20:41:20 +090013427Convert uppercase characters to lowercase and lowercase characters to uppercase.
13428[clinic start generated code]*/
13429
13430static PyObject *
13431unicode_swapcase_impl(PyObject *self)
13432/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013433{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013434 if (PyUnicode_READY(self) == -1)
13435 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013436 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013437}
13438
Larry Hastings61272b72014-01-07 12:41:53 -080013439/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013440
Larry Hastings31826802013-10-19 00:09:25 -070013441@staticmethod
13442str.maketrans as unicode_maketrans
13443
13444 x: object
13445
13446 y: unicode=NULL
13447
13448 z: unicode=NULL
13449
13450 /
13451
13452Return a translation table usable for str.translate().
13453
13454If there is only one argument, it must be a dictionary mapping Unicode
13455ordinals (integers) or characters to Unicode ordinals, strings or None.
13456Character keys will be then converted to ordinals.
13457If there are two arguments, they must be strings of equal length, and
13458in the resulting dictionary, each character in x will be mapped to the
13459character at the same position in y. If there is a third argument, it
13460must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013461[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013462
Larry Hastings31826802013-10-19 00:09:25 -070013463static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013464unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013465/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013466{
Georg Brandlceee0772007-11-27 23:48:05 +000013467 PyObject *new = NULL, *key, *value;
13468 Py_ssize_t i = 0;
13469 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013470
Georg Brandlceee0772007-11-27 23:48:05 +000013471 new = PyDict_New();
13472 if (!new)
13473 return NULL;
13474 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013475 int x_kind, y_kind, z_kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013476 const void *x_data, *y_data, *z_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013477
Georg Brandlceee0772007-11-27 23:48:05 +000013478 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013479 if (!PyUnicode_Check(x)) {
13480 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13481 "be a string if there is a second argument");
13482 goto err;
13483 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013484 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013485 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13486 "arguments must have equal length");
13487 goto err;
13488 }
13489 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013490 x_kind = PyUnicode_KIND(x);
13491 y_kind = PyUnicode_KIND(y);
13492 x_data = PyUnicode_DATA(x);
13493 y_data = PyUnicode_DATA(y);
13494 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13495 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013496 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013497 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013498 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013499 if (!value) {
13500 Py_DECREF(key);
13501 goto err;
13502 }
Georg Brandlceee0772007-11-27 23:48:05 +000013503 res = PyDict_SetItem(new, key, value);
13504 Py_DECREF(key);
13505 Py_DECREF(value);
13506 if (res < 0)
13507 goto err;
13508 }
13509 /* create entries for deleting chars in z */
13510 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013511 z_kind = PyUnicode_KIND(z);
13512 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013513 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013514 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013515 if (!key)
13516 goto err;
13517 res = PyDict_SetItem(new, key, Py_None);
13518 Py_DECREF(key);
13519 if (res < 0)
13520 goto err;
13521 }
13522 }
13523 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013524 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013525 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013526
Georg Brandlceee0772007-11-27 23:48:05 +000013527 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013528 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013529 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13530 "to maketrans it must be a dict");
13531 goto err;
13532 }
13533 /* copy entries into the new dict, converting string keys to int keys */
13534 while (PyDict_Next(x, &i, &key, &value)) {
13535 if (PyUnicode_Check(key)) {
13536 /* convert string keys to integer keys */
13537 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013538 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013539 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13540 "table must be of length 1");
13541 goto err;
13542 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013543 kind = PyUnicode_KIND(key);
13544 data = PyUnicode_DATA(key);
13545 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013546 if (!newkey)
13547 goto err;
13548 res = PyDict_SetItem(new, newkey, value);
13549 Py_DECREF(newkey);
13550 if (res < 0)
13551 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013552 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013553 /* just keep integer keys */
13554 if (PyDict_SetItem(new, key, value) < 0)
13555 goto err;
13556 } else {
13557 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13558 "be strings or integers");
13559 goto err;
13560 }
13561 }
13562 }
13563 return new;
13564 err:
13565 Py_DECREF(new);
13566 return NULL;
13567}
13568
INADA Naoki3ae20562017-01-16 20:41:20 +090013569/*[clinic input]
13570str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013571
INADA Naoki3ae20562017-01-16 20:41:20 +090013572 table: object
13573 Translation table, which must be a mapping of Unicode ordinals to
13574 Unicode ordinals, strings, or None.
13575 /
13576
13577Replace each character in the string using the given translation table.
13578
13579The table must implement lookup/indexing via __getitem__, for instance a
13580dictionary or list. If this operation raises LookupError, the character is
13581left untouched. Characters mapped to None are deleted.
13582[clinic start generated code]*/
13583
13584static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013585unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013586/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013587{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013588 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013589}
13590
INADA Naoki3ae20562017-01-16 20:41:20 +090013591/*[clinic input]
13592str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013593
INADA Naoki3ae20562017-01-16 20:41:20 +090013594Return a copy of the string converted to uppercase.
13595[clinic start generated code]*/
13596
13597static PyObject *
13598unicode_upper_impl(PyObject *self)
13599/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013600{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013601 if (PyUnicode_READY(self) == -1)
13602 return NULL;
13603 if (PyUnicode_IS_ASCII(self))
13604 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013605 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013606}
13607
INADA Naoki3ae20562017-01-16 20:41:20 +090013608/*[clinic input]
13609str.zfill as unicode_zfill
13610
13611 width: Py_ssize_t
13612 /
13613
13614Pad a numeric string with zeros on the left, to fill a field of the given width.
13615
13616The string is never truncated.
13617[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013618
13619static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013620unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013621/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013622{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013623 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013624 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013625 int kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030013626 const void *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013627 Py_UCS4 chr;
13628
Benjamin Petersonbac79492012-01-14 13:34:47 -050013629 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013630 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013631
Victor Stinnerc4b49542011-12-11 22:44:26 +010013632 if (PyUnicode_GET_LENGTH(self) >= width)
13633 return unicode_result_unchanged(self);
13634
13635 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013636
13637 u = pad(self, fill, 0, '0');
13638
Walter Dörwald068325e2002-04-15 13:36:47 +000013639 if (u == NULL)
13640 return NULL;
13641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013642 kind = PyUnicode_KIND(u);
13643 data = PyUnicode_DATA(u);
13644 chr = PyUnicode_READ(kind, data, fill);
13645
13646 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013647 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013648 PyUnicode_WRITE(kind, data, 0, chr);
13649 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013650 }
13651
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013652 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013653 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013654}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013655
13656#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013657static PyObject *
13658unicode__decimal2ascii(PyObject *self)
13659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013660 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013661}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013662#endif
13663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013664PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013665 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013666\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013667Return True if S starts with the specified prefix, False otherwise.\n\
13668With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013669With optional end, stop comparing S at that position.\n\
13670prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013671
13672static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013673unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013675{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013676 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013677 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013678 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013679 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013680 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013681
Jesus Ceaac451502011-04-20 17:09:23 +020013682 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013684 if (PyTuple_Check(subobj)) {
13685 Py_ssize_t i;
13686 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013687 substring = PyTuple_GET_ITEM(subobj, i);
13688 if (!PyUnicode_Check(substring)) {
13689 PyErr_Format(PyExc_TypeError,
13690 "tuple for startswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013691 "not %.100s",
13692 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013693 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013694 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013695 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013696 if (result == -1)
13697 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013698 if (result) {
13699 Py_RETURN_TRUE;
13700 }
13701 }
13702 /* nothing matched */
13703 Py_RETURN_FALSE;
13704 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013705 if (!PyUnicode_Check(subobj)) {
13706 PyErr_Format(PyExc_TypeError,
13707 "startswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013708 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013709 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013710 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013711 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013712 if (result == -1)
13713 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013714 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013715}
13716
13717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013718PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013719 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013720\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013721Return True if S ends with the specified suffix, False otherwise.\n\
13722With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013723With optional end, stop comparing S at that position.\n\
13724suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013725
13726static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013727unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013728 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013729{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013730 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013731 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013732 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013733 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013734 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013735
Jesus Ceaac451502011-04-20 17:09:23 +020013736 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013737 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013738 if (PyTuple_Check(subobj)) {
13739 Py_ssize_t i;
13740 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013741 substring = PyTuple_GET_ITEM(subobj, i);
13742 if (!PyUnicode_Check(substring)) {
13743 PyErr_Format(PyExc_TypeError,
13744 "tuple for endswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013745 "not %.100s",
13746 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013747 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013748 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013749 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013750 if (result == -1)
13751 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013752 if (result) {
13753 Py_RETURN_TRUE;
13754 }
13755 }
13756 Py_RETURN_FALSE;
13757 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013758 if (!PyUnicode_Check(subobj)) {
13759 PyErr_Format(PyExc_TypeError,
13760 "endswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013761 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013762 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013763 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013764 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013765 if (result == -1)
13766 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013767 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013768}
13769
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013770static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013771_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013772{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013773 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13774 writer->data = PyUnicode_DATA(writer->buffer);
13775
13776 if (!writer->readonly) {
13777 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013778 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013779 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013780 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013781 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13782 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13783 writer->kind = PyUnicode_WCHAR_KIND;
13784 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13785
Victor Stinner8f674cc2013-04-17 23:02:17 +020013786 /* Copy-on-write mode: set buffer size to 0 so
13787 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13788 * next write. */
13789 writer->size = 0;
13790 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013791}
13792
Victor Stinnerd3f08822012-05-29 12:57:52 +020013793void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013794_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013795{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013796 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013797
13798 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013799 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013800
13801 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13802 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13803 writer->kind = PyUnicode_WCHAR_KIND;
13804 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013805}
13806
Inada Naoki770847a2019-06-24 12:30:24 +090013807// Initialize _PyUnicodeWriter with initial buffer
13808static inline void
13809_PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer)
13810{
13811 memset(writer, 0, sizeof(*writer));
13812 writer->buffer = buffer;
13813 _PyUnicodeWriter_Update(writer);
13814 writer->min_length = writer->size;
13815}
13816
Victor Stinnerd3f08822012-05-29 12:57:52 +020013817int
13818_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13819 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013820{
13821 Py_ssize_t newlen;
13822 PyObject *newbuffer;
13823
Victor Stinner2740e462016-09-06 16:58:36 -070013824 assert(maxchar <= MAX_UNICODE);
13825
Victor Stinnerca9381e2015-09-22 00:58:32 +020013826 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013827 assert((maxchar > writer->maxchar && length >= 0)
13828 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013829
Victor Stinner202fdca2012-05-07 12:47:02 +020013830 if (length > PY_SSIZE_T_MAX - writer->pos) {
13831 PyErr_NoMemory();
13832 return -1;
13833 }
13834 newlen = writer->pos + length;
13835
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013836 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013837
Victor Stinnerd3f08822012-05-29 12:57:52 +020013838 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013839 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013840 if (writer->overallocate
13841 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13842 /* overallocate to limit the number of realloc() */
13843 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013844 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013845 if (newlen < writer->min_length)
13846 newlen = writer->min_length;
13847
Victor Stinnerd3f08822012-05-29 12:57:52 +020013848 writer->buffer = PyUnicode_New(newlen, maxchar);
13849 if (writer->buffer == NULL)
13850 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013851 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013852 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013853 if (writer->overallocate
13854 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13855 /* overallocate to limit the number of realloc() */
13856 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013857 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013858 if (newlen < writer->min_length)
13859 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013860
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013861 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013862 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013863 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013864 newbuffer = PyUnicode_New(newlen, maxchar);
13865 if (newbuffer == NULL)
13866 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013867 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13868 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013869 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013870 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013871 }
13872 else {
13873 newbuffer = resize_compact(writer->buffer, newlen);
13874 if (newbuffer == NULL)
13875 return -1;
13876 }
13877 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013878 }
13879 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013880 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013881 newbuffer = PyUnicode_New(writer->size, maxchar);
13882 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013883 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013884 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13885 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013886 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013887 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013888 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013889 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013890
13891#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013892}
13893
Victor Stinnerca9381e2015-09-22 00:58:32 +020013894int
13895_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13896 enum PyUnicode_Kind kind)
13897{
13898 Py_UCS4 maxchar;
13899
13900 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13901 assert(writer->kind < kind);
13902
13903 switch (kind)
13904 {
13905 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13906 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13907 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13908 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013909 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013910 }
13911
13912 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13913}
13914
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013915static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013916_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013917{
Victor Stinner2740e462016-09-06 16:58:36 -070013918 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013919 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13920 return -1;
13921 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13922 writer->pos++;
13923 return 0;
13924}
13925
13926int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013927_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13928{
13929 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13930}
13931
13932int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013933_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13934{
13935 Py_UCS4 maxchar;
13936 Py_ssize_t len;
13937
13938 if (PyUnicode_READY(str) == -1)
13939 return -1;
13940 len = PyUnicode_GET_LENGTH(str);
13941 if (len == 0)
13942 return 0;
13943 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13944 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013945 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013946 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013947 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013948 Py_INCREF(str);
13949 writer->buffer = str;
13950 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013951 writer->pos += len;
13952 return 0;
13953 }
13954 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13955 return -1;
13956 }
13957 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13958 str, 0, len);
13959 writer->pos += len;
13960 return 0;
13961}
13962
Victor Stinnere215d962012-10-06 23:03:36 +020013963int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013964_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13965 Py_ssize_t start, Py_ssize_t end)
13966{
13967 Py_UCS4 maxchar;
13968 Py_ssize_t len;
13969
13970 if (PyUnicode_READY(str) == -1)
13971 return -1;
13972
13973 assert(0 <= start);
13974 assert(end <= PyUnicode_GET_LENGTH(str));
13975 assert(start <= end);
13976
13977 if (end == 0)
13978 return 0;
13979
13980 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13981 return _PyUnicodeWriter_WriteStr(writer, str);
13982
13983 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13984 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13985 else
13986 maxchar = writer->maxchar;
13987 len = end - start;
13988
13989 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13990 return -1;
13991
13992 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13993 str, start, len);
13994 writer->pos += len;
13995 return 0;
13996}
13997
13998int
Victor Stinner4a587072013-11-19 12:54:53 +010013999_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
14000 const char *ascii, Py_ssize_t len)
14001{
14002 if (len == -1)
14003 len = strlen(ascii);
14004
Andy Lestere6be9b52020-02-11 20:28:35 -060014005 assert(ucs1lib_find_max_char((const Py_UCS1*)ascii, (const Py_UCS1*)ascii + len) < 128);
Victor Stinner4a587072013-11-19 12:54:53 +010014006
14007 if (writer->buffer == NULL && !writer->overallocate) {
14008 PyObject *str;
14009
14010 str = _PyUnicode_FromASCII(ascii, len);
14011 if (str == NULL)
14012 return -1;
14013
14014 writer->readonly = 1;
14015 writer->buffer = str;
14016 _PyUnicodeWriter_Update(writer);
14017 writer->pos += len;
14018 return 0;
14019 }
14020
14021 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
14022 return -1;
14023
14024 switch (writer->kind)
14025 {
14026 case PyUnicode_1BYTE_KIND:
14027 {
14028 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
14029 Py_UCS1 *data = writer->data;
14030
Christian Heimesf051e432016-09-13 20:22:02 +020014031 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010014032 break;
14033 }
14034 case PyUnicode_2BYTE_KIND:
14035 {
14036 _PyUnicode_CONVERT_BYTES(
14037 Py_UCS1, Py_UCS2,
14038 ascii, ascii + len,
14039 (Py_UCS2 *)writer->data + writer->pos);
14040 break;
14041 }
14042 case PyUnicode_4BYTE_KIND:
14043 {
14044 _PyUnicode_CONVERT_BYTES(
14045 Py_UCS1, Py_UCS4,
14046 ascii, ascii + len,
14047 (Py_UCS4 *)writer->data + writer->pos);
14048 break;
14049 }
14050 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014051 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010014052 }
14053
14054 writer->pos += len;
14055 return 0;
14056}
14057
14058int
14059_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
14060 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020014061{
14062 Py_UCS4 maxchar;
14063
Andy Lestere6be9b52020-02-11 20:28:35 -060014064 maxchar = ucs1lib_find_max_char((const Py_UCS1*)str, (const Py_UCS1*)str + len);
Victor Stinnere215d962012-10-06 23:03:36 +020014065 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
14066 return -1;
14067 unicode_write_cstr(writer->buffer, writer->pos, str, len);
14068 writer->pos += len;
14069 return 0;
14070}
14071
Victor Stinnerd3f08822012-05-29 12:57:52 +020014072PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020014073_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020014074{
Victor Stinner15a0bd32013-07-08 22:29:55 +020014075 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030014076
Victor Stinnerd3f08822012-05-29 12:57:52 +020014077 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020014078 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020014079 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020014080 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030014081
14082 str = writer->buffer;
14083 writer->buffer = NULL;
14084
Victor Stinnerd7b7c742012-06-04 22:52:12 +020014085 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020014086 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
14087 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014088 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020014089
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030014090 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
14091 PyObject *str2;
14092 str2 = resize_compact(str, writer->pos);
14093 if (str2 == NULL) {
14094 Py_DECREF(str);
14095 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020014096 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030014097 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020014098 }
14099
Victor Stinner15a0bd32013-07-08 22:29:55 +020014100 assert(_PyUnicode_CheckConsistency(str, 1));
14101 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020014102}
14103
Victor Stinnerd3f08822012-05-29 12:57:52 +020014104void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020014105_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020014106{
14107 Py_CLEAR(writer->buffer);
14108}
14109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014110#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000014111
14112PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000014113 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000014114\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000014115Return a formatted version of S, using substitutions from args and kwargs.\n\
14116The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000014117
Eric Smith27bbca62010-11-04 17:06:58 +000014118PyDoc_STRVAR(format_map__doc__,
14119 "S.format_map(mapping) -> str\n\
14120\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000014121Return a formatted version of S, using substitutions from mapping.\n\
14122The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000014123
INADA Naoki3ae20562017-01-16 20:41:20 +090014124/*[clinic input]
14125str.__format__ as unicode___format__
14126
14127 format_spec: unicode
14128 /
14129
14130Return a formatted version of the string as described by format_spec.
14131[clinic start generated code]*/
14132
Eric Smith4a7d76d2008-05-30 18:10:19 +000014133static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090014134unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090014135/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000014136{
Victor Stinnerd3f08822012-05-29 12:57:52 +020014137 _PyUnicodeWriter writer;
14138 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000014139
Victor Stinnerd3f08822012-05-29 12:57:52 +020014140 if (PyUnicode_READY(self) == -1)
14141 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020014142 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014143 ret = _PyUnicode_FormatAdvancedWriter(&writer,
14144 self, format_spec, 0,
14145 PyUnicode_GET_LENGTH(format_spec));
14146 if (ret == -1) {
14147 _PyUnicodeWriter_Dealloc(&writer);
14148 return NULL;
14149 }
14150 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000014151}
14152
INADA Naoki3ae20562017-01-16 20:41:20 +090014153/*[clinic input]
14154str.__sizeof__ as unicode_sizeof
14155
14156Return the size of the string in memory, in bytes.
14157[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000014158
14159static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090014160unicode_sizeof_impl(PyObject *self)
14161/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000014162{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014163 Py_ssize_t size;
14164
14165 /* If it's a compact object, account for base structure +
14166 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090014167 if (PyUnicode_IS_COMPACT_ASCII(self))
14168 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
14169 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014170 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090014171 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014172 else {
14173 /* If it is a two-block object, account for base object, and
14174 for character block if present. */
14175 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090014176 if (_PyUnicode_DATA_ANY(self))
14177 size += (PyUnicode_GET_LENGTH(self) + 1) *
14178 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014179 }
14180 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020014181 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090014182 if (_PyUnicode_HAS_WSTR_MEMORY(self))
14183 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
14184 if (_PyUnicode_HAS_UTF8_MEMORY(self))
14185 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014186
14187 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000014188}
14189
Georg Brandlc28e1fa2008-06-10 19:20:26 +000014190static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053014191unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000014192{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010014193 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014194 if (!copy)
14195 return NULL;
14196 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000014197}
14198
Guido van Rossumd57fd912000-03-10 22:53:23 +000014199static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090014200 UNICODE_ENCODE_METHODDEF
14201 UNICODE_REPLACE_METHODDEF
14202 UNICODE_SPLIT_METHODDEF
14203 UNICODE_RSPLIT_METHODDEF
14204 UNICODE_JOIN_METHODDEF
14205 UNICODE_CAPITALIZE_METHODDEF
14206 UNICODE_CASEFOLD_METHODDEF
14207 UNICODE_TITLE_METHODDEF
14208 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000014209 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090014210 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000014211 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090014212 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000014213 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090014214 UNICODE_LJUST_METHODDEF
14215 UNICODE_LOWER_METHODDEF
14216 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000014217 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
14218 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090014219 UNICODE_RJUST_METHODDEF
14220 UNICODE_RSTRIP_METHODDEF
14221 UNICODE_RPARTITION_METHODDEF
14222 UNICODE_SPLITLINES_METHODDEF
14223 UNICODE_STRIP_METHODDEF
14224 UNICODE_SWAPCASE_METHODDEF
14225 UNICODE_TRANSLATE_METHODDEF
14226 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000014227 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
14228 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
sweeneydea81849b2020-04-22 17:05:48 -040014229 UNICODE_REMOVEPREFIX_METHODDEF
14230 UNICODE_REMOVESUFFIX_METHODDEF
INADA Naokia49ac992018-01-27 14:06:21 +090014231 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090014232 UNICODE_ISLOWER_METHODDEF
14233 UNICODE_ISUPPER_METHODDEF
14234 UNICODE_ISTITLE_METHODDEF
14235 UNICODE_ISSPACE_METHODDEF
14236 UNICODE_ISDECIMAL_METHODDEF
14237 UNICODE_ISDIGIT_METHODDEF
14238 UNICODE_ISNUMERIC_METHODDEF
14239 UNICODE_ISALPHA_METHODDEF
14240 UNICODE_ISALNUM_METHODDEF
14241 UNICODE_ISIDENTIFIER_METHODDEF
14242 UNICODE_ISPRINTABLE_METHODDEF
14243 UNICODE_ZFILL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +020014244 {"format", (PyCFunction)(void(*)(void)) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000014245 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090014246 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070014247 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090014248 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000014249#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000014250 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000014251 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000014252#endif
14253
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053014254 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000014255 {NULL, NULL}
14256};
14257
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014258static PyObject *
14259unicode_mod(PyObject *v, PyObject *w)
14260{
Brian Curtindfc80e32011-08-10 20:28:54 -050014261 if (!PyUnicode_Check(v))
14262 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000014263 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014264}
14265
14266static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014267 0, /*nb_add*/
14268 0, /*nb_subtract*/
14269 0, /*nb_multiply*/
14270 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000014271};
14272
Guido van Rossumd57fd912000-03-10 22:53:23 +000014273static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014274 (lenfunc) unicode_length, /* sq_length */
14275 PyUnicode_Concat, /* sq_concat */
14276 (ssizeargfunc) unicode_repeat, /* sq_repeat */
14277 (ssizeargfunc) unicode_getitem, /* sq_item */
14278 0, /* sq_slice */
14279 0, /* sq_ass_item */
14280 0, /* sq_ass_slice */
14281 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014282};
14283
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014284static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014285unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014286{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014287 if (PyUnicode_READY(self) == -1)
14288 return NULL;
14289
Victor Stinnera15e2602020-04-08 02:01:56 +020014290 if (_PyIndex_Check(item)) {
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000014291 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014292 if (i == -1 && PyErr_Occurred())
14293 return NULL;
14294 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014295 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014296 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014297 } else if (PySlice_Check(item)) {
Zackery Spytz14514d92019-05-17 01:13:03 -060014298 Py_ssize_t start, stop, step, slicelength, i;
14299 size_t cur;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014300 PyObject *result;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030014301 const void *src_data;
14302 void *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014303 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014304 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014305
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014306 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014307 return NULL;
14308 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014309 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14310 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014311
14312 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020014313 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014314 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010014315 slicelength == PyUnicode_GET_LENGTH(self)) {
14316 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000014317 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014318 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020014319 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014320 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014321 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014322 src_kind = PyUnicode_KIND(self);
14323 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020014324 if (!PyUnicode_IS_ASCII(self)) {
14325 kind_limit = kind_maxchar_limit(src_kind);
14326 max_char = 0;
14327 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14328 ch = PyUnicode_READ(src_kind, src_data, cur);
14329 if (ch > max_char) {
14330 max_char = ch;
14331 if (max_char >= kind_limit)
14332 break;
14333 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014334 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014335 }
Victor Stinner55c99112011-10-13 01:17:06 +020014336 else
14337 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014338 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014339 if (result == NULL)
14340 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014341 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014342 dest_data = PyUnicode_DATA(result);
14343
14344 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014345 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14346 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014347 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014348 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014349 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014350 } else {
14351 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14352 return NULL;
14353 }
14354}
14355
14356static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014357 (lenfunc)unicode_length, /* mp_length */
14358 (binaryfunc)unicode_subscript, /* mp_subscript */
14359 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014360};
14361
Guido van Rossumd57fd912000-03-10 22:53:23 +000014362
Guido van Rossumd57fd912000-03-10 22:53:23 +000014363/* Helpers for PyUnicode_Format() */
14364
Victor Stinnera47082312012-10-04 02:19:54 +020014365struct unicode_formatter_t {
14366 PyObject *args;
14367 int args_owned;
14368 Py_ssize_t arglen, argidx;
14369 PyObject *dict;
14370
14371 enum PyUnicode_Kind fmtkind;
14372 Py_ssize_t fmtcnt, fmtpos;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030014373 const void *fmtdata;
Victor Stinnera47082312012-10-04 02:19:54 +020014374 PyObject *fmtstr;
14375
14376 _PyUnicodeWriter writer;
14377};
14378
14379struct unicode_format_arg_t {
14380 Py_UCS4 ch;
14381 int flags;
14382 Py_ssize_t width;
14383 int prec;
14384 int sign;
14385};
14386
Guido van Rossumd57fd912000-03-10 22:53:23 +000014387static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014388unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014389{
Victor Stinnera47082312012-10-04 02:19:54 +020014390 Py_ssize_t argidx = ctx->argidx;
14391
14392 if (argidx < ctx->arglen) {
14393 ctx->argidx++;
14394 if (ctx->arglen < 0)
14395 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014396 else
Victor Stinnera47082312012-10-04 02:19:54 +020014397 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014398 }
14399 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014400 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014401 return NULL;
14402}
14403
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014404/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014405
Victor Stinnera47082312012-10-04 02:19:54 +020014406/* Format a float into the writer if the writer is not NULL, or into *p_output
14407 otherwise.
14408
14409 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014410static int
Victor Stinnera47082312012-10-04 02:19:54 +020014411formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14412 PyObject **p_output,
14413 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014414{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014415 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014416 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014417 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014418 int prec;
14419 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014420
Guido van Rossumd57fd912000-03-10 22:53:23 +000014421 x = PyFloat_AsDouble(v);
14422 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014423 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014424
Victor Stinnera47082312012-10-04 02:19:54 +020014425 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014426 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014427 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014428
Victor Stinnera47082312012-10-04 02:19:54 +020014429 if (arg->flags & F_ALT)
14430 dtoa_flags = Py_DTSF_ALT;
14431 else
14432 dtoa_flags = 0;
14433 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014434 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014435 return -1;
14436 len = strlen(p);
14437 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014438 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014439 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014440 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014441 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014442 }
14443 else
14444 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014445 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014446 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014447}
14448
Victor Stinnerd0880d52012-04-27 23:40:13 +020014449/* formatlong() emulates the format codes d, u, o, x and X, and
14450 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14451 * Python's regular ints.
14452 * Return value: a new PyUnicodeObject*, or NULL if error.
14453 * The output string is of the form
14454 * "-"? ("0x" | "0X")? digit+
14455 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14456 * set in flags. The case of hex digits will be correct,
14457 * There will be at least prec digits, zero-filled on the left if
14458 * necessary to get that many.
14459 * val object to be converted
14460 * flags bitmask of format flags; only F_ALT is looked at
14461 * prec minimum number of digits; 0-fill on left if needed
14462 * type a character in [duoxX]; u acts the same as d
14463 *
14464 * CAUTION: o, x and X conversions on regular ints can never
14465 * produce a '-' sign, but can for Python's unbounded ints.
14466 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014467PyObject *
14468_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014469{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014470 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014471 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014472 Py_ssize_t i;
14473 int sign; /* 1 if '-', else 0 */
14474 int len; /* number of characters */
14475 Py_ssize_t llen;
14476 int numdigits; /* len == numnondigits + numdigits */
14477 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014478
Victor Stinnerd0880d52012-04-27 23:40:13 +020014479 /* Avoid exceeding SSIZE_T_MAX */
14480 if (prec > INT_MAX-3) {
14481 PyErr_SetString(PyExc_OverflowError,
14482 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014483 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014484 }
14485
14486 assert(PyLong_Check(val));
14487
14488 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014489 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014490 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014491 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014492 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014493 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014494 /* int and int subclasses should print numerically when a numeric */
14495 /* format code is used (see issue18780) */
14496 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014497 break;
14498 case 'o':
14499 numnondigits = 2;
14500 result = PyNumber_ToBase(val, 8);
14501 break;
14502 case 'x':
14503 case 'X':
14504 numnondigits = 2;
14505 result = PyNumber_ToBase(val, 16);
14506 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014507 }
14508 if (!result)
14509 return NULL;
14510
14511 assert(unicode_modifiable(result));
14512 assert(PyUnicode_IS_READY(result));
14513 assert(PyUnicode_IS_ASCII(result));
14514
14515 /* To modify the string in-place, there can only be one reference. */
14516 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014517 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014518 PyErr_BadInternalCall();
14519 return NULL;
14520 }
14521 buf = PyUnicode_DATA(result);
14522 llen = PyUnicode_GET_LENGTH(result);
14523 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014524 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014525 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014526 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014527 return NULL;
14528 }
14529 len = (int)llen;
14530 sign = buf[0] == '-';
14531 numnondigits += sign;
14532 numdigits = len - numnondigits;
14533 assert(numdigits > 0);
14534
14535 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014536 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014537 (type == 'o' || type == 'x' || type == 'X'))) {
14538 assert(buf[sign] == '0');
14539 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14540 buf[sign+1] == 'o');
14541 numnondigits -= 2;
14542 buf += 2;
14543 len -= 2;
14544 if (sign)
14545 buf[0] = '-';
14546 assert(len == numnondigits + numdigits);
14547 assert(numdigits > 0);
14548 }
14549
14550 /* Fill with leading zeroes to meet minimum width. */
14551 if (prec > numdigits) {
14552 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14553 numnondigits + prec);
14554 char *b1;
14555 if (!r1) {
14556 Py_DECREF(result);
14557 return NULL;
14558 }
14559 b1 = PyBytes_AS_STRING(r1);
14560 for (i = 0; i < numnondigits; ++i)
14561 *b1++ = *buf++;
14562 for (i = 0; i < prec - numdigits; i++)
14563 *b1++ = '0';
14564 for (i = 0; i < numdigits; i++)
14565 *b1++ = *buf++;
14566 *b1 = '\0';
14567 Py_DECREF(result);
14568 result = r1;
14569 buf = PyBytes_AS_STRING(result);
14570 len = numnondigits + prec;
14571 }
14572
14573 /* Fix up case for hex conversions. */
14574 if (type == 'X') {
14575 /* Need to convert all lower case letters to upper case.
14576 and need to convert 0x to 0X (and -0x to -0X). */
14577 for (i = 0; i < len; i++)
14578 if (buf[i] >= 'a' && buf[i] <= 'x')
14579 buf[i] -= 'a'-'A';
14580 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014581 if (!PyUnicode_Check(result)
14582 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014583 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014584 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014585 Py_DECREF(result);
14586 result = unicode;
14587 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014588 else if (len != PyUnicode_GET_LENGTH(result)) {
14589 if (PyUnicode_Resize(&result, len) < 0)
14590 Py_CLEAR(result);
14591 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014592 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014593}
14594
Ethan Furmandf3ed242014-01-05 06:50:30 -080014595/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014596 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014597 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014598 * -1 and raise an exception on error */
14599static int
Victor Stinnera47082312012-10-04 02:19:54 +020014600mainformatlong(PyObject *v,
14601 struct unicode_format_arg_t *arg,
14602 PyObject **p_output,
14603 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014604{
14605 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014606 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014607
14608 if (!PyNumber_Check(v))
14609 goto wrongtype;
14610
Ethan Furman9ab74802014-03-21 06:38:46 -070014611 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014612 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014613 if (type == 'o' || type == 'x' || type == 'X') {
14614 iobj = PyNumber_Index(v);
14615 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014616 if (PyErr_ExceptionMatches(PyExc_TypeError))
14617 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014618 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014619 }
14620 }
14621 else {
14622 iobj = PyNumber_Long(v);
14623 if (iobj == NULL ) {
14624 if (PyErr_ExceptionMatches(PyExc_TypeError))
14625 goto wrongtype;
14626 return -1;
14627 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014628 }
14629 assert(PyLong_Check(iobj));
14630 }
14631 else {
14632 iobj = v;
14633 Py_INCREF(iobj);
14634 }
14635
14636 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014637 && arg->width == -1 && arg->prec == -1
14638 && !(arg->flags & (F_SIGN | F_BLANK))
14639 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014640 {
14641 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014642 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014643 int base;
14644
Victor Stinnera47082312012-10-04 02:19:54 +020014645 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014646 {
14647 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014648 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014649 case 'd':
14650 case 'i':
14651 case 'u':
14652 base = 10;
14653 break;
14654 case 'o':
14655 base = 8;
14656 break;
14657 case 'x':
14658 case 'X':
14659 base = 16;
14660 break;
14661 }
14662
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014663 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14664 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014665 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014666 }
14667 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014668 return 1;
14669 }
14670
Ethan Furmanb95b5612015-01-23 20:05:18 -080014671 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014672 Py_DECREF(iobj);
14673 if (res == NULL)
14674 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014675 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014676 return 0;
14677
14678wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014679 switch(type)
14680 {
14681 case 'o':
14682 case 'x':
14683 case 'X':
14684 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014685 "%%%c format: an integer is required, "
14686 "not %.200s",
14687 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014688 break;
14689 default:
14690 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014691 "%%%c format: a number is required, "
14692 "not %.200s",
14693 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014694 break;
14695 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014696 return -1;
14697}
14698
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014699static Py_UCS4
14700formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014701{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014702 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014703 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014704 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014705 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014706 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014707 goto onError;
14708 }
14709 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014710 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014711 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014712 /* make sure number is a type of integer */
14713 if (!PyLong_Check(v)) {
14714 iobj = PyNumber_Index(v);
14715 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014716 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014717 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014718 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014719 Py_DECREF(iobj);
14720 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014721 else {
14722 x = PyLong_AsLong(v);
14723 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014724 if (x == -1 && PyErr_Occurred())
14725 goto onError;
14726
Victor Stinner8faf8212011-12-08 22:14:11 +010014727 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014728 PyErr_SetString(PyExc_OverflowError,
14729 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014730 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014731 }
14732
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014733 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014734 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014735
Benjamin Peterson29060642009-01-31 22:14:21 +000014736 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014737 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014738 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014739 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014740}
14741
Victor Stinnera47082312012-10-04 02:19:54 +020014742/* Parse options of an argument: flags, width, precision.
14743 Handle also "%(name)" syntax.
14744
14745 Return 0 if the argument has been formatted into arg->str.
14746 Return 1 if the argument has been written into ctx->writer,
14747 Raise an exception and return -1 on error. */
14748static int
14749unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14750 struct unicode_format_arg_t *arg)
14751{
14752#define FORMAT_READ(ctx) \
14753 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14754
14755 PyObject *v;
14756
Victor Stinnera47082312012-10-04 02:19:54 +020014757 if (arg->ch == '(') {
14758 /* Get argument value from a dictionary. Example: "%(name)s". */
14759 Py_ssize_t keystart;
14760 Py_ssize_t keylen;
14761 PyObject *key;
14762 int pcount = 1;
14763
14764 if (ctx->dict == NULL) {
14765 PyErr_SetString(PyExc_TypeError,
14766 "format requires a mapping");
14767 return -1;
14768 }
14769 ++ctx->fmtpos;
14770 --ctx->fmtcnt;
14771 keystart = ctx->fmtpos;
14772 /* Skip over balanced parentheses */
14773 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14774 arg->ch = FORMAT_READ(ctx);
14775 if (arg->ch == ')')
14776 --pcount;
14777 else if (arg->ch == '(')
14778 ++pcount;
14779 ctx->fmtpos++;
14780 }
14781 keylen = ctx->fmtpos - keystart - 1;
14782 if (ctx->fmtcnt < 0 || pcount > 0) {
14783 PyErr_SetString(PyExc_ValueError,
14784 "incomplete format key");
14785 return -1;
14786 }
14787 key = PyUnicode_Substring(ctx->fmtstr,
14788 keystart, keystart + keylen);
14789 if (key == NULL)
14790 return -1;
14791 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014792 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014793 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014794 }
14795 ctx->args = PyObject_GetItem(ctx->dict, key);
14796 Py_DECREF(key);
14797 if (ctx->args == NULL)
14798 return -1;
14799 ctx->args_owned = 1;
14800 ctx->arglen = -1;
14801 ctx->argidx = -2;
14802 }
14803
14804 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014805 while (--ctx->fmtcnt >= 0) {
14806 arg->ch = FORMAT_READ(ctx);
14807 ctx->fmtpos++;
14808 switch (arg->ch) {
14809 case '-': arg->flags |= F_LJUST; continue;
14810 case '+': arg->flags |= F_SIGN; continue;
14811 case ' ': arg->flags |= F_BLANK; continue;
14812 case '#': arg->flags |= F_ALT; continue;
14813 case '0': arg->flags |= F_ZERO; continue;
14814 }
14815 break;
14816 }
14817
14818 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014819 if (arg->ch == '*') {
14820 v = unicode_format_getnextarg(ctx);
14821 if (v == NULL)
14822 return -1;
14823 if (!PyLong_Check(v)) {
14824 PyErr_SetString(PyExc_TypeError,
14825 "* wants int");
14826 return -1;
14827 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014828 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014829 if (arg->width == -1 && PyErr_Occurred())
14830 return -1;
14831 if (arg->width < 0) {
14832 arg->flags |= F_LJUST;
14833 arg->width = -arg->width;
14834 }
14835 if (--ctx->fmtcnt >= 0) {
14836 arg->ch = FORMAT_READ(ctx);
14837 ctx->fmtpos++;
14838 }
14839 }
14840 else if (arg->ch >= '0' && arg->ch <= '9') {
14841 arg->width = arg->ch - '0';
14842 while (--ctx->fmtcnt >= 0) {
14843 arg->ch = FORMAT_READ(ctx);
14844 ctx->fmtpos++;
14845 if (arg->ch < '0' || arg->ch > '9')
14846 break;
14847 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14848 mixing signed and unsigned comparison. Since arg->ch is between
14849 '0' and '9', casting to int is safe. */
14850 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14851 PyErr_SetString(PyExc_ValueError,
14852 "width too big");
14853 return -1;
14854 }
14855 arg->width = arg->width*10 + (arg->ch - '0');
14856 }
14857 }
14858
14859 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014860 if (arg->ch == '.') {
14861 arg->prec = 0;
14862 if (--ctx->fmtcnt >= 0) {
14863 arg->ch = FORMAT_READ(ctx);
14864 ctx->fmtpos++;
14865 }
14866 if (arg->ch == '*') {
14867 v = unicode_format_getnextarg(ctx);
14868 if (v == NULL)
14869 return -1;
14870 if (!PyLong_Check(v)) {
14871 PyErr_SetString(PyExc_TypeError,
14872 "* wants int");
14873 return -1;
14874 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014875 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014876 if (arg->prec == -1 && PyErr_Occurred())
14877 return -1;
14878 if (arg->prec < 0)
14879 arg->prec = 0;
14880 if (--ctx->fmtcnt >= 0) {
14881 arg->ch = FORMAT_READ(ctx);
14882 ctx->fmtpos++;
14883 }
14884 }
14885 else if (arg->ch >= '0' && arg->ch <= '9') {
14886 arg->prec = arg->ch - '0';
14887 while (--ctx->fmtcnt >= 0) {
14888 arg->ch = FORMAT_READ(ctx);
14889 ctx->fmtpos++;
14890 if (arg->ch < '0' || arg->ch > '9')
14891 break;
14892 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14893 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014894 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014895 return -1;
14896 }
14897 arg->prec = arg->prec*10 + (arg->ch - '0');
14898 }
14899 }
14900 }
14901
14902 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14903 if (ctx->fmtcnt >= 0) {
14904 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14905 if (--ctx->fmtcnt >= 0) {
14906 arg->ch = FORMAT_READ(ctx);
14907 ctx->fmtpos++;
14908 }
14909 }
14910 }
14911 if (ctx->fmtcnt < 0) {
14912 PyErr_SetString(PyExc_ValueError,
14913 "incomplete format");
14914 return -1;
14915 }
14916 return 0;
14917
14918#undef FORMAT_READ
14919}
14920
14921/* Format one argument. Supported conversion specifiers:
14922
14923 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014924 - "i", "d", "u": int or float
14925 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014926 - "e", "E", "f", "F", "g", "G": float
14927 - "c": int or str (1 character)
14928
Victor Stinner8dbd4212012-12-04 09:30:24 +010014929 When possible, the output is written directly into the Unicode writer
14930 (ctx->writer). A string is created when padding is required.
14931
Victor Stinnera47082312012-10-04 02:19:54 +020014932 Return 0 if the argument has been formatted into *p_str,
14933 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014934 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014935static int
14936unicode_format_arg_format(struct unicode_formatter_t *ctx,
14937 struct unicode_format_arg_t *arg,
14938 PyObject **p_str)
14939{
14940 PyObject *v;
14941 _PyUnicodeWriter *writer = &ctx->writer;
14942
14943 if (ctx->fmtcnt == 0)
14944 ctx->writer.overallocate = 0;
14945
Victor Stinnera47082312012-10-04 02:19:54 +020014946 v = unicode_format_getnextarg(ctx);
14947 if (v == NULL)
14948 return -1;
14949
Victor Stinnera47082312012-10-04 02:19:54 +020014950
14951 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014952 case 's':
14953 case 'r':
14954 case 'a':
14955 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14956 /* Fast path */
14957 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14958 return -1;
14959 return 1;
14960 }
14961
14962 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14963 *p_str = v;
14964 Py_INCREF(*p_str);
14965 }
14966 else {
14967 if (arg->ch == 's')
14968 *p_str = PyObject_Str(v);
14969 else if (arg->ch == 'r')
14970 *p_str = PyObject_Repr(v);
14971 else
14972 *p_str = PyObject_ASCII(v);
14973 }
14974 break;
14975
14976 case 'i':
14977 case 'd':
14978 case 'u':
14979 case 'o':
14980 case 'x':
14981 case 'X':
14982 {
14983 int ret = mainformatlong(v, arg, p_str, writer);
14984 if (ret != 0)
14985 return ret;
14986 arg->sign = 1;
14987 break;
14988 }
14989
14990 case 'e':
14991 case 'E':
14992 case 'f':
14993 case 'F':
14994 case 'g':
14995 case 'G':
14996 if (arg->width == -1 && arg->prec == -1
14997 && !(arg->flags & (F_SIGN | F_BLANK)))
14998 {
14999 /* Fast path */
15000 if (formatfloat(v, arg, NULL, writer) == -1)
15001 return -1;
15002 return 1;
15003 }
15004
15005 arg->sign = 1;
15006 if (formatfloat(v, arg, p_str, NULL) == -1)
15007 return -1;
15008 break;
15009
15010 case 'c':
15011 {
15012 Py_UCS4 ch = formatchar(v);
15013 if (ch == (Py_UCS4) -1)
15014 return -1;
15015 if (arg->width == -1 && arg->prec == -1) {
15016 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020015017 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020015018 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020015019 return 1;
15020 }
15021 *p_str = PyUnicode_FromOrdinal(ch);
15022 break;
15023 }
15024
15025 default:
15026 PyErr_Format(PyExc_ValueError,
15027 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020015028 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020015029 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
15030 (int)arg->ch,
15031 ctx->fmtpos - 1);
15032 return -1;
15033 }
15034 if (*p_str == NULL)
15035 return -1;
15036 assert (PyUnicode_Check(*p_str));
15037 return 0;
15038}
15039
15040static int
15041unicode_format_arg_output(struct unicode_formatter_t *ctx,
15042 struct unicode_format_arg_t *arg,
15043 PyObject *str)
15044{
15045 Py_ssize_t len;
15046 enum PyUnicode_Kind kind;
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030015047 const void *pbuf;
Victor Stinnera47082312012-10-04 02:19:54 +020015048 Py_ssize_t pindex;
15049 Py_UCS4 signchar;
15050 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020015051 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020015052 Py_ssize_t sublen;
15053 _PyUnicodeWriter *writer = &ctx->writer;
15054 Py_UCS4 fill;
15055
15056 fill = ' ';
15057 if (arg->sign && arg->flags & F_ZERO)
15058 fill = '0';
15059
15060 if (PyUnicode_READY(str) == -1)
15061 return -1;
15062
15063 len = PyUnicode_GET_LENGTH(str);
15064 if ((arg->width == -1 || arg->width <= len)
15065 && (arg->prec == -1 || arg->prec >= len)
15066 && !(arg->flags & (F_SIGN | F_BLANK)))
15067 {
15068 /* Fast path */
15069 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
15070 return -1;
15071 return 0;
15072 }
15073
15074 /* Truncate the string for "s", "r" and "a" formats
15075 if the precision is set */
15076 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
15077 if (arg->prec >= 0 && len > arg->prec)
15078 len = arg->prec;
15079 }
15080
15081 /* Adjust sign and width */
15082 kind = PyUnicode_KIND(str);
15083 pbuf = PyUnicode_DATA(str);
15084 pindex = 0;
15085 signchar = '\0';
15086 if (arg->sign) {
15087 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
15088 if (ch == '-' || ch == '+') {
15089 signchar = ch;
15090 len--;
15091 pindex++;
15092 }
15093 else if (arg->flags & F_SIGN)
15094 signchar = '+';
15095 else if (arg->flags & F_BLANK)
15096 signchar = ' ';
15097 else
15098 arg->sign = 0;
15099 }
15100 if (arg->width < len)
15101 arg->width = len;
15102
15103 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020015104 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020015105 if (!(arg->flags & F_LJUST)) {
15106 if (arg->sign) {
15107 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070015108 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020015109 }
15110 else {
15111 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070015112 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020015113 }
15114 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020015115 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
15116 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070015117 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020015118 }
15119
Victor Stinnera47082312012-10-04 02:19:54 +020015120 buflen = arg->width;
15121 if (arg->sign && len == arg->width)
15122 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020015123 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020015124 return -1;
15125
15126 /* Write the sign if needed */
15127 if (arg->sign) {
15128 if (fill != ' ') {
15129 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
15130 writer->pos += 1;
15131 }
15132 if (arg->width > len)
15133 arg->width--;
15134 }
15135
15136 /* Write the numeric prefix for "x", "X" and "o" formats
15137 if the alternate form is used.
15138 For example, write "0x" for the "%#x" format. */
15139 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
15140 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
15141 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
15142 if (fill != ' ') {
15143 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
15144 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
15145 writer->pos += 2;
15146 pindex += 2;
15147 }
15148 arg->width -= 2;
15149 if (arg->width < 0)
15150 arg->width = 0;
15151 len -= 2;
15152 }
15153
15154 /* Pad left with the fill character if needed */
15155 if (arg->width > len && !(arg->flags & F_LJUST)) {
15156 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010015157 unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020015158 writer->pos += sublen;
15159 arg->width = len;
15160 }
15161
15162 /* If padding with spaces: write sign if needed and/or numeric prefix if
15163 the alternate form is used */
15164 if (fill == ' ') {
15165 if (arg->sign) {
15166 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
15167 writer->pos += 1;
15168 }
15169 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
15170 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
15171 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
15172 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
15173 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
15174 writer->pos += 2;
15175 pindex += 2;
15176 }
15177 }
15178
15179 /* Write characters */
15180 if (len) {
15181 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
15182 str, pindex, len);
15183 writer->pos += len;
15184 }
15185
15186 /* Pad right with the fill character if needed */
15187 if (arg->width > len) {
15188 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010015189 unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020015190 writer->pos += sublen;
15191 }
15192 return 0;
15193}
15194
15195/* Helper of PyUnicode_Format(): format one arg.
15196 Return 0 on success, raise an exception and return -1 on error. */
15197static int
15198unicode_format_arg(struct unicode_formatter_t *ctx)
15199{
15200 struct unicode_format_arg_t arg;
15201 PyObject *str;
15202 int ret;
15203
Victor Stinner8dbd4212012-12-04 09:30:24 +010015204 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020015205 if (arg.ch == '%') {
15206 ctx->fmtpos++;
15207 ctx->fmtcnt--;
15208 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
15209 return -1;
15210 return 0;
15211 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010015212 arg.flags = 0;
15213 arg.width = -1;
15214 arg.prec = -1;
15215 arg.sign = 0;
15216 str = NULL;
15217
Victor Stinnera47082312012-10-04 02:19:54 +020015218 ret = unicode_format_arg_parse(ctx, &arg);
15219 if (ret == -1)
15220 return -1;
15221
15222 ret = unicode_format_arg_format(ctx, &arg, &str);
15223 if (ret == -1)
15224 return -1;
15225
15226 if (ret != 1) {
15227 ret = unicode_format_arg_output(ctx, &arg, str);
15228 Py_DECREF(str);
15229 if (ret == -1)
15230 return -1;
15231 }
15232
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020015233 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020015234 PyErr_SetString(PyExc_TypeError,
15235 "not all arguments converted during string formatting");
15236 return -1;
15237 }
15238 return 0;
15239}
15240
Alexander Belopolsky40018472011-02-26 01:02:56 +000015241PyObject *
15242PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015243{
Victor Stinnera47082312012-10-04 02:19:54 +020015244 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000015245
Guido van Rossumd57fd912000-03-10 22:53:23 +000015246 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015247 PyErr_BadInternalCall();
15248 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015249 }
Victor Stinnera47082312012-10-04 02:19:54 +020015250
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030015251 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015252 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030015253
15254 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020015255 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
15256 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
15257 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
15258 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020015259
Victor Stinner8f674cc2013-04-17 23:02:17 +020015260 _PyUnicodeWriter_Init(&ctx.writer);
15261 ctx.writer.min_length = ctx.fmtcnt + 100;
15262 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020015263
Guido van Rossumd57fd912000-03-10 22:53:23 +000015264 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020015265 ctx.arglen = PyTuple_Size(args);
15266 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015267 }
15268 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015269 ctx.arglen = -1;
15270 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015271 }
Victor Stinnera47082312012-10-04 02:19:54 +020015272 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040015273 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020015274 ctx.dict = args;
15275 else
15276 ctx.dict = NULL;
15277 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015278
Victor Stinnera47082312012-10-04 02:19:54 +020015279 while (--ctx.fmtcnt >= 0) {
15280 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020015281 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020015282
15283 nonfmtpos = ctx.fmtpos++;
15284 while (ctx.fmtcnt >= 0 &&
15285 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
15286 ctx.fmtpos++;
15287 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015288 }
Victor Stinnera47082312012-10-04 02:19:54 +020015289 if (ctx.fmtcnt < 0) {
15290 ctx.fmtpos--;
15291 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020015292 }
Victor Stinneree4544c2012-05-09 22:24:08 +020015293
Victor Stinnercfc4c132013-04-03 01:48:39 +020015294 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
15295 nonfmtpos, ctx.fmtpos) < 0)
15296 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015297 }
15298 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015299 ctx.fmtpos++;
15300 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000015301 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020015302 }
15303 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020015304
Victor Stinnera47082312012-10-04 02:19:54 +020015305 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015306 PyErr_SetString(PyExc_TypeError,
15307 "not all arguments converted during string formatting");
15308 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015309 }
15310
Victor Stinnera47082312012-10-04 02:19:54 +020015311 if (ctx.args_owned) {
15312 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015313 }
Victor Stinnera47082312012-10-04 02:19:54 +020015314 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015315
Benjamin Peterson29060642009-01-31 22:14:21 +000015316 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020015317 _PyUnicodeWriter_Dealloc(&ctx.writer);
15318 if (ctx.args_owned) {
15319 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015320 }
15321 return NULL;
15322}
15323
Jeremy Hylton938ace62002-07-17 16:30:39 +000015324static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000015325unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
15326
Tim Peters6d6c1a32001-08-02 04:15:00 +000015327static PyObject *
15328unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15329{
Benjamin Peterson29060642009-01-31 22:14:21 +000015330 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015331 static char *kwlist[] = {"object", "encoding", "errors", 0};
15332 char *encoding = NULL;
15333 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015334
Benjamin Peterson14339b62009-01-31 16:36:08 +000015335 if (type != &PyUnicode_Type)
15336 return unicode_subtype_new(type, args, kwds);
15337 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015338 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015339 return NULL;
15340 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015341 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015342 if (encoding == NULL && errors == NULL)
15343 return PyObject_Str(x);
15344 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015345 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015346}
15347
Guido van Rossume023fe02001-08-30 03:12:59 +000015348static PyObject *
15349unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15350{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015351 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015352 Py_ssize_t length, char_size;
15353 int share_wstr, share_utf8;
15354 unsigned int kind;
15355 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015356
Benjamin Peterson14339b62009-01-31 16:36:08 +000015357 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015358
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015359 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015360 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015361 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015362 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015363 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015364 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015365 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015366 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015367
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015368 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015369 if (self == NULL) {
15370 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015371 return NULL;
15372 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015373 kind = PyUnicode_KIND(unicode);
15374 length = PyUnicode_GET_LENGTH(unicode);
15375
15376 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015377#ifdef Py_DEBUG
15378 _PyUnicode_HASH(self) = -1;
15379#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015380 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015381#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015382 _PyUnicode_STATE(self).interned = 0;
15383 _PyUnicode_STATE(self).kind = kind;
15384 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015385 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015386 _PyUnicode_STATE(self).ready = 1;
15387 _PyUnicode_WSTR(self) = NULL;
15388 _PyUnicode_UTF8_LENGTH(self) = 0;
15389 _PyUnicode_UTF8(self) = NULL;
15390 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015391 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015392
15393 share_utf8 = 0;
15394 share_wstr = 0;
15395 if (kind == PyUnicode_1BYTE_KIND) {
15396 char_size = 1;
15397 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15398 share_utf8 = 1;
15399 }
15400 else if (kind == PyUnicode_2BYTE_KIND) {
15401 char_size = 2;
15402 if (sizeof(wchar_t) == 2)
15403 share_wstr = 1;
15404 }
15405 else {
15406 assert(kind == PyUnicode_4BYTE_KIND);
15407 char_size = 4;
15408 if (sizeof(wchar_t) == 4)
15409 share_wstr = 1;
15410 }
15411
15412 /* Ensure we won't overflow the length. */
15413 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15414 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015415 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015416 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015417 data = PyObject_MALLOC((length + 1) * char_size);
15418 if (data == NULL) {
15419 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015420 goto onError;
15421 }
15422
Victor Stinnerc3c74152011-10-02 20:39:55 +020015423 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015424 if (share_utf8) {
15425 _PyUnicode_UTF8_LENGTH(self) = length;
15426 _PyUnicode_UTF8(self) = data;
15427 }
15428 if (share_wstr) {
15429 _PyUnicode_WSTR_LENGTH(self) = length;
15430 _PyUnicode_WSTR(self) = (wchar_t *)data;
15431 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015432
Christian Heimesf051e432016-09-13 20:22:02 +020015433 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015434 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015435 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015436#ifdef Py_DEBUG
15437 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15438#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015439 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015440 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015441
15442onError:
15443 Py_DECREF(unicode);
15444 Py_DECREF(self);
15445 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015446}
15447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015448PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015449"str(object='') -> str\n\
15450str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015451\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015452Create a new string object from the given object. If encoding or\n\
15453errors is specified, then the object must expose a data buffer\n\
15454that will be decoded using the given encoding and error handler.\n\
15455Otherwise, returns the result of object.__str__() (if defined)\n\
15456or repr(object).\n\
15457encoding defaults to sys.getdefaultencoding().\n\
15458errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015459
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015460static PyObject *unicode_iter(PyObject *seq);
15461
Guido van Rossumd57fd912000-03-10 22:53:23 +000015462PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015463 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015464 "str", /* tp_name */
15465 sizeof(PyUnicodeObject), /* tp_basicsize */
15466 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015467 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015468 (destructor)unicode_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020015469 0, /* tp_vectorcall_offset */
Bupfc93bd42018-06-19 03:59:55 -050015470 0, /* tp_getattr */
15471 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020015472 0, /* tp_as_async */
Bupfc93bd42018-06-19 03:59:55 -050015473 unicode_repr, /* tp_repr */
15474 &unicode_as_number, /* tp_as_number */
15475 &unicode_as_sequence, /* tp_as_sequence */
15476 &unicode_as_mapping, /* tp_as_mapping */
15477 (hashfunc) unicode_hash, /* tp_hash*/
15478 0, /* tp_call*/
15479 (reprfunc) unicode_str, /* tp_str */
15480 PyObject_GenericGetAttr, /* tp_getattro */
15481 0, /* tp_setattro */
15482 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015483 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015484 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15485 unicode_doc, /* tp_doc */
15486 0, /* tp_traverse */
15487 0, /* tp_clear */
15488 PyUnicode_RichCompare, /* tp_richcompare */
15489 0, /* tp_weaklistoffset */
15490 unicode_iter, /* tp_iter */
15491 0, /* tp_iternext */
15492 unicode_methods, /* tp_methods */
15493 0, /* tp_members */
15494 0, /* tp_getset */
15495 &PyBaseObject_Type, /* tp_base */
15496 0, /* tp_dict */
15497 0, /* tp_descr_get */
15498 0, /* tp_descr_set */
15499 0, /* tp_dictoffset */
15500 0, /* tp_init */
15501 0, /* tp_alloc */
15502 unicode_new, /* tp_new */
15503 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015504};
15505
15506/* Initialize the Unicode implementation */
15507
Victor Stinner331a6a52019-05-27 16:39:22 +020015508PyStatus
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015509_PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015510{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015511 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015512 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015513 0x000A, /* LINE FEED */
15514 0x000D, /* CARRIAGE RETURN */
15515 0x001C, /* FILE SEPARATOR */
15516 0x001D, /* GROUP SEPARATOR */
15517 0x001E, /* RECORD SEPARATOR */
15518 0x0085, /* NEXT LINE */
15519 0x2028, /* LINE SEPARATOR */
15520 0x2029, /* PARAGRAPH SEPARATOR */
15521 };
15522
Fred Drakee4315f52000-05-09 19:53:39 +000015523 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015524 _Py_INCREF_UNICODE_EMPTY();
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015525 if (!unicode_empty) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015526 return _PyStatus_ERR("Can't create empty string");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015527 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020015528 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015529
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015530 if (PyType_Ready(&PyUnicode_Type) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015531 return _PyStatus_ERR("Can't initialize unicode type");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015532 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015533
15534 /* initialize the linebreak bloom filter */
15535 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015536 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015537 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015538
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015539 if (PyType_Ready(&EncodingMapType) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015540 return _PyStatus_ERR("Can't initialize encoding map type");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015541 }
15542 if (PyType_Ready(&PyFieldNameIter_Type) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015543 return _PyStatus_ERR("Can't initialize field name iterator type");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015544 }
15545 if (PyType_Ready(&PyFormatterIter_Type) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020015546 return _PyStatus_ERR("Can't initialize formatter iter type");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015547 }
Victor Stinner331a6a52019-05-27 16:39:22 +020015548 return _PyStatus_OK();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015549}
15550
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015551
Walter Dörwald16807132007-05-25 13:52:07 +000015552void
15553PyUnicode_InternInPlace(PyObject **p)
15554{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015555 PyObject *s = *p;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015556#ifdef Py_DEBUG
15557 assert(s != NULL);
15558 assert(_PyUnicode_CHECK(s));
15559#else
Victor Stinner607b1022020-05-05 18:50:30 +020015560 if (s == NULL || !PyUnicode_Check(s)) {
Victor Stinner4fae54c2011-10-03 02:01:52 +020015561 return;
Victor Stinner607b1022020-05-05 18:50:30 +020015562 }
Victor Stinner4fae54c2011-10-03 02:01:52 +020015563#endif
Victor Stinner607b1022020-05-05 18:50:30 +020015564
Benjamin Peterson14339b62009-01-31 16:36:08 +000015565 /* If it's a subclass, we don't really know what putting
15566 it in the interned dict might do. */
Victor Stinner607b1022020-05-05 18:50:30 +020015567 if (!PyUnicode_CheckExact(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015568 return;
Victor Stinner607b1022020-05-05 18:50:30 +020015569 }
15570
15571 if (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015572 return;
Victor Stinner607b1022020-05-05 18:50:30 +020015573 }
15574
15575#ifdef INTERNED_STRINGS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015576 if (interned == NULL) {
15577 interned = PyDict_New();
15578 if (interned == NULL) {
15579 PyErr_Clear(); /* Don't leave an exception */
15580 return;
15581 }
15582 }
Victor Stinner607b1022020-05-05 18:50:30 +020015583
15584 PyObject *t;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015585 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015586 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015587 Py_END_ALLOW_RECURSION
Victor Stinner607b1022020-05-05 18:50:30 +020015588
Berker Peksagced8d4c2016-07-25 04:40:39 +030015589 if (t == NULL) {
15590 PyErr_Clear();
15591 return;
15592 }
Victor Stinner607b1022020-05-05 18:50:30 +020015593
Berker Peksagced8d4c2016-07-25 04:40:39 +030015594 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015595 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015596 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015597 return;
15598 }
Victor Stinner607b1022020-05-05 18:50:30 +020015599
Benjamin Peterson14339b62009-01-31 16:36:08 +000015600 /* The two references in interned are not counted by refcnt.
15601 The deallocator will take care of this */
Victor Stinnerc86a1122020-02-07 01:24:29 +010015602 Py_SET_REFCNT(s, Py_REFCNT(s) - 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015603 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Victor Stinner607b1022020-05-05 18:50:30 +020015604#endif
Walter Dörwald16807132007-05-25 13:52:07 +000015605}
15606
15607void
15608PyUnicode_InternImmortal(PyObject **p)
15609{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015610 PyUnicode_InternInPlace(p);
15611 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015612 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015613 Py_INCREF(*p);
15614 }
Walter Dörwald16807132007-05-25 13:52:07 +000015615}
15616
15617PyObject *
15618PyUnicode_InternFromString(const char *cp)
15619{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015620 PyObject *s = PyUnicode_FromString(cp);
15621 if (s == NULL)
15622 return NULL;
15623 PyUnicode_InternInPlace(&s);
15624 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015625}
15626
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015627
15628#if defined(WITH_VALGRIND) || defined(__INSURE__)
15629static void
15630unicode_release_interned(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015631{
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015632 if (interned == NULL || !PyDict_Check(interned)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015633 return;
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015634 }
15635 PyObject *keys = PyDict_Keys(interned);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015636 if (keys == NULL || !PyList_Check(keys)) {
15637 PyErr_Clear();
15638 return;
15639 }
Walter Dörwald16807132007-05-25 13:52:07 +000015640
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015641 /* Since unicode_release_interned() is intended to help a leak
Benjamin Peterson14339b62009-01-31 16:36:08 +000015642 detector, interned unicode strings are not forcibly deallocated;
15643 rather, we give them their stolen references back, and then clear
15644 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015645
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015646 Py_ssize_t n = PyList_GET_SIZE(keys);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015647#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015648 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015649 n);
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015650
15651 Py_ssize_t immortal_size = 0, mortal_size = 0;
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015652#endif
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015653 for (Py_ssize_t i = 0; i < n; i++) {
15654 PyObject *s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015655 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015656 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015657 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015658 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015659 case SSTATE_INTERNED_IMMORTAL:
15660 Py_REFCNT(s) += 1;
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015661#ifdef INTERNED_STATS
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015662 immortal_size += PyUnicode_GET_LENGTH(s);
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015663#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015664 break;
15665 case SSTATE_INTERNED_MORTAL:
15666 Py_REFCNT(s) += 2;
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015667#ifdef INTERNED_STATS
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015668 mortal_size += PyUnicode_GET_LENGTH(s);
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015669#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015670 break;
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015671 case SSTATE_NOT_INTERNED:
15672 /* fall through */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015673 default:
Victor Stinnerec3c99c2020-01-30 12:18:32 +010015674 Py_UNREACHABLE();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015676 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015677 }
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015678#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015679 fprintf(stderr, "total size of all interned strings: "
15680 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15681 "mortal/immortal\n", mortal_size, immortal_size);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015682#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015683 Py_DECREF(keys);
15684 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015685 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015686}
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015687#endif
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015688
15689
15690/********************* Unicode Iterator **************************/
15691
15692typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015693 PyObject_HEAD
15694 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015695 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015696} unicodeiterobject;
15697
15698static void
15699unicodeiter_dealloc(unicodeiterobject *it)
15700{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015701 _PyObject_GC_UNTRACK(it);
15702 Py_XDECREF(it->it_seq);
15703 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015704}
15705
15706static int
15707unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15708{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015709 Py_VISIT(it->it_seq);
15710 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015711}
15712
15713static PyObject *
15714unicodeiter_next(unicodeiterobject *it)
15715{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015716 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015717
Benjamin Peterson14339b62009-01-31 16:36:08 +000015718 assert(it != NULL);
15719 seq = it->it_seq;
15720 if (seq == NULL)
15721 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015722 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015723
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015724 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15725 int kind = PyUnicode_KIND(seq);
Serhiy Storchakacd8295f2020-04-11 10:48:40 +030015726 const void *data = PyUnicode_DATA(seq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015727 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15728 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015729 if (item != NULL)
15730 ++it->it_index;
15731 return item;
15732 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015733
Benjamin Peterson14339b62009-01-31 16:36:08 +000015734 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015735 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015736 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015737}
15738
15739static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015740unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015741{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015742 Py_ssize_t len = 0;
15743 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015744 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015745 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015746}
15747
15748PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15749
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015750static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015751unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015752{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015753 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015754 if (it->it_seq != NULL) {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015755 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015756 it->it_seq, it->it_index);
15757 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015758 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015759 if (u == NULL)
15760 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015761 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015762 }
15763}
15764
15765PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15766
15767static PyObject *
15768unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15769{
15770 Py_ssize_t index = PyLong_AsSsize_t(state);
15771 if (index == -1 && PyErr_Occurred())
15772 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015773 if (it->it_seq != NULL) {
15774 if (index < 0)
15775 index = 0;
15776 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15777 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15778 it->it_index = index;
15779 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015780 Py_RETURN_NONE;
15781}
15782
15783PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15784
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015785static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015786 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015787 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015788 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15789 reduce_doc},
15790 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15791 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015792 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015793};
15794
15795PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015796 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15797 "str_iterator", /* tp_name */
15798 sizeof(unicodeiterobject), /* tp_basicsize */
15799 0, /* tp_itemsize */
15800 /* methods */
15801 (destructor)unicodeiter_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020015802 0, /* tp_vectorcall_offset */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015803 0, /* tp_getattr */
15804 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020015805 0, /* tp_as_async */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015806 0, /* tp_repr */
15807 0, /* tp_as_number */
15808 0, /* tp_as_sequence */
15809 0, /* tp_as_mapping */
15810 0, /* tp_hash */
15811 0, /* tp_call */
15812 0, /* tp_str */
15813 PyObject_GenericGetAttr, /* tp_getattro */
15814 0, /* tp_setattro */
15815 0, /* tp_as_buffer */
15816 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15817 0, /* tp_doc */
15818 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15819 0, /* tp_clear */
15820 0, /* tp_richcompare */
15821 0, /* tp_weaklistoffset */
15822 PyObject_SelfIter, /* tp_iter */
15823 (iternextfunc)unicodeiter_next, /* tp_iternext */
15824 unicodeiter_methods, /* tp_methods */
15825 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015826};
15827
15828static PyObject *
15829unicode_iter(PyObject *seq)
15830{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015831 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015832
Benjamin Peterson14339b62009-01-31 16:36:08 +000015833 if (!PyUnicode_Check(seq)) {
15834 PyErr_BadInternalCall();
15835 return NULL;
15836 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015837 if (PyUnicode_READY(seq) == -1)
15838 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015839 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15840 if (it == NULL)
15841 return NULL;
15842 it->it_index = 0;
15843 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015844 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015845 _PyObject_GC_TRACK(it);
15846 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015847}
15848
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015849
15850size_t
15851Py_UNICODE_strlen(const Py_UNICODE *u)
15852{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015853 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015854}
15855
15856Py_UNICODE*
15857Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15858{
15859 Py_UNICODE *u = s1;
15860 while ((*u++ = *s2++));
15861 return s1;
15862}
15863
15864Py_UNICODE*
15865Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15866{
15867 Py_UNICODE *u = s1;
15868 while ((*u++ = *s2++))
15869 if (n-- == 0)
15870 break;
15871 return s1;
15872}
15873
15874Py_UNICODE*
15875Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15876{
15877 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015878 u1 += wcslen(u1);
15879 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015880 return s1;
15881}
15882
15883int
15884Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15885{
15886 while (*s1 && *s2 && *s1 == *s2)
15887 s1++, s2++;
15888 if (*s1 && *s2)
15889 return (*s1 < *s2) ? -1 : +1;
15890 if (*s1)
15891 return 1;
15892 if (*s2)
15893 return -1;
15894 return 0;
15895}
15896
15897int
15898Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15899{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015900 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015901 for (; n != 0; n--) {
15902 u1 = *s1;
15903 u2 = *s2;
15904 if (u1 != u2)
15905 return (u1 < u2) ? -1 : +1;
15906 if (u1 == '\0')
15907 return 0;
15908 s1++;
15909 s2++;
15910 }
15911 return 0;
15912}
15913
15914Py_UNICODE*
15915Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15916{
15917 const Py_UNICODE *p;
15918 for (p = s; *p; p++)
15919 if (*p == c)
15920 return (Py_UNICODE*)p;
15921 return NULL;
15922}
15923
15924Py_UNICODE*
15925Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15926{
15927 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015928 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015929 while (p != s) {
15930 p--;
15931 if (*p == c)
15932 return (Py_UNICODE*)p;
15933 }
15934 return NULL;
15935}
Victor Stinner331ea922010-08-10 16:37:20 +000015936
Victor Stinner71133ff2010-09-01 23:43:53 +000015937Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015938PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015939{
Victor Stinner577db2c2011-10-11 22:12:48 +020015940 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015941 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015943 if (!PyUnicode_Check(unicode)) {
15944 PyErr_BadArgument();
15945 return NULL;
15946 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015947 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015948 if (u == NULL)
15949 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015950 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015951 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015952 PyErr_NoMemory();
15953 return NULL;
15954 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015955 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015956 size *= sizeof(Py_UNICODE);
15957 copy = PyMem_Malloc(size);
15958 if (copy == NULL) {
15959 PyErr_NoMemory();
15960 return NULL;
15961 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015962 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015963 return copy;
15964}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015965
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015966
Victor Stinner709d23d2019-05-02 14:56:30 -040015967static int
15968encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015969{
Victor Stinner709d23d2019-05-02 14:56:30 -040015970 int res;
15971 res = _Py_EncodeUTF8Ex(wstr, str, NULL, NULL, 1, _Py_ERROR_STRICT);
15972 if (res == -2) {
15973 PyErr_Format(PyExc_RuntimeWarning, "cannot decode %s", name);
15974 return -1;
15975 }
15976 if (res < 0) {
15977 PyErr_NoMemory();
15978 return -1;
15979 }
15980 return 0;
15981}
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015982
Victor Stinner709d23d2019-05-02 14:56:30 -040015983
15984static int
15985config_get_codec_name(wchar_t **config_encoding)
15986{
15987 char *encoding;
15988 if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
15989 return -1;
15990 }
15991
15992 PyObject *name_obj = NULL;
15993 PyObject *codec = _PyCodec_Lookup(encoding);
15994 PyMem_RawFree(encoding);
15995
Victor Stinner43fc3bb2019-05-02 11:54:20 -040015996 if (!codec)
15997 goto error;
15998
15999 name_obj = PyObject_GetAttrString(codec, "name");
16000 Py_CLEAR(codec);
16001 if (!name_obj) {
16002 goto error;
16003 }
16004
Victor Stinner709d23d2019-05-02 14:56:30 -040016005 wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
16006 Py_DECREF(name_obj);
16007 if (wname == NULL) {
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016008 goto error;
16009 }
16010
Victor Stinner709d23d2019-05-02 14:56:30 -040016011 wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
16012 if (raw_wname == NULL) {
16013 PyMem_Free(wname);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016014 PyErr_NoMemory();
Victor Stinner709d23d2019-05-02 14:56:30 -040016015 goto error;
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016016 }
Victor Stinner709d23d2019-05-02 14:56:30 -040016017
16018 PyMem_RawFree(*config_encoding);
16019 *config_encoding = raw_wname;
16020
16021 PyMem_Free(wname);
16022 return 0;
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016023
16024error:
16025 Py_XDECREF(codec);
16026 Py_XDECREF(name_obj);
Victor Stinner709d23d2019-05-02 14:56:30 -040016027 return -1;
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016028}
16029
16030
Victor Stinner331a6a52019-05-27 16:39:22 +020016031static PyStatus
Victor Stinnerfcdb0272019-09-23 14:45:47 +020016032init_stdio_encoding(PyThreadState *tstate)
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016033{
Victor Stinner709d23d2019-05-02 14:56:30 -040016034 /* Update the stdio encoding to the normalized Python codec name. */
Victor Stinnerda7933e2020-04-13 03:04:28 +020016035 PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(tstate->interp);
Victor Stinner709d23d2019-05-02 14:56:30 -040016036 if (config_get_codec_name(&config->stdio_encoding) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020016037 return _PyStatus_ERR("failed to get the Python codec name "
Victor Stinnerfcdb0272019-09-23 14:45:47 +020016038 "of the stdio encoding");
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016039 }
Victor Stinner331a6a52019-05-27 16:39:22 +020016040 return _PyStatus_OK();
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016041}
16042
16043
Victor Stinner709d23d2019-05-02 14:56:30 -040016044static int
16045init_fs_codec(PyInterpreterState *interp)
16046{
Victor Stinnerda7933e2020-04-13 03:04:28 +020016047 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -040016048
16049 _Py_error_handler error_handler;
16050 error_handler = get_error_handler_wide(config->filesystem_errors);
16051 if (error_handler == _Py_ERROR_UNKNOWN) {
16052 PyErr_SetString(PyExc_RuntimeError, "unknow filesystem error handler");
16053 return -1;
16054 }
16055
16056 char *encoding, *errors;
16057 if (encode_wstr_utf8(config->filesystem_encoding,
16058 &encoding,
16059 "filesystem_encoding") < 0) {
16060 return -1;
16061 }
16062
16063 if (encode_wstr_utf8(config->filesystem_errors,
16064 &errors,
16065 "filesystem_errors") < 0) {
16066 PyMem_RawFree(encoding);
16067 return -1;
16068 }
16069
Victor Stinner3d17c042020-05-14 01:48:38 +020016070 struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
16071 PyMem_RawFree(fs_codec->encoding);
16072 fs_codec->encoding = encoding;
Victor Stinnerbf305cc2020-02-05 17:39:57 +010016073 /* encoding has been normalized by init_fs_encoding() */
Victor Stinner3d17c042020-05-14 01:48:38 +020016074 fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
16075 PyMem_RawFree(fs_codec->errors);
16076 fs_codec->errors = errors;
16077 fs_codec->error_handler = error_handler;
Victor Stinner709d23d2019-05-02 14:56:30 -040016078
Victor Stinnerbf305cc2020-02-05 17:39:57 +010016079#ifdef _Py_FORCE_UTF8_FS_ENCODING
Victor Stinner3d17c042020-05-14 01:48:38 +020016080 assert(fs_codec->utf8 == 1);
Victor Stinnerbf305cc2020-02-05 17:39:57 +010016081#endif
16082
Victor Stinner709d23d2019-05-02 14:56:30 -040016083 /* At this point, PyUnicode_EncodeFSDefault() and
16084 PyUnicode_DecodeFSDefault() can now use the Python codec rather than
16085 the C implementation of the filesystem encoding. */
16086
16087 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
16088 global configuration variables. */
Victor Stinner3d17c042020-05-14 01:48:38 +020016089 if (_Py_SetFileSystemEncoding(fs_codec->encoding,
16090 fs_codec->errors) < 0) {
Victor Stinner709d23d2019-05-02 14:56:30 -040016091 PyErr_NoMemory();
16092 return -1;
16093 }
16094 return 0;
16095}
16096
16097
Victor Stinner331a6a52019-05-27 16:39:22 +020016098static PyStatus
Victor Stinnerfcdb0272019-09-23 14:45:47 +020016099init_fs_encoding(PyThreadState *tstate)
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016100{
Victor Stinnerfcdb0272019-09-23 14:45:47 +020016101 PyInterpreterState *interp = tstate->interp;
16102
Victor Stinner709d23d2019-05-02 14:56:30 -040016103 /* Update the filesystem encoding to the normalized Python codec name.
16104 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
16105 (Python codec name). */
Victor Stinnerda7933e2020-04-13 03:04:28 +020016106 PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -040016107 if (config_get_codec_name(&config->filesystem_encoding) < 0) {
Victor Stinnerfcdb0272019-09-23 14:45:47 +020016108 _Py_DumpPathConfig(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020016109 return _PyStatus_ERR("failed to get the Python codec "
Victor Stinnerfcdb0272019-09-23 14:45:47 +020016110 "of the filesystem encoding");
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016111 }
16112
Victor Stinner709d23d2019-05-02 14:56:30 -040016113 if (init_fs_codec(interp) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +020016114 return _PyStatus_ERR("cannot initialize filesystem codec");
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016115 }
Victor Stinner331a6a52019-05-27 16:39:22 +020016116 return _PyStatus_OK();
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016117}
16118
16119
Victor Stinner331a6a52019-05-27 16:39:22 +020016120PyStatus
Victor Stinnerb45d2592019-06-20 00:05:23 +020016121_PyUnicode_InitEncodings(PyThreadState *tstate)
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016122{
Victor Stinnerfcdb0272019-09-23 14:45:47 +020016123 PyStatus status = init_fs_encoding(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +020016124 if (_PyStatus_EXCEPTION(status)) {
16125 return status;
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016126 }
16127
Victor Stinnerfcdb0272019-09-23 14:45:47 +020016128 return init_stdio_encoding(tstate);
Victor Stinner43fc3bb2019-05-02 11:54:20 -040016129}
16130
16131
Victor Stinnerbf305cc2020-02-05 17:39:57 +010016132static void
Victor Stinner3d17c042020-05-14 01:48:38 +020016133_PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
Victor Stinnerbf305cc2020-02-05 17:39:57 +010016134{
Victor Stinner3d17c042020-05-14 01:48:38 +020016135 PyMem_RawFree(fs_codec->encoding);
16136 fs_codec->encoding = NULL;
16137 fs_codec->utf8 = 0;
16138 PyMem_RawFree(fs_codec->errors);
16139 fs_codec->errors = NULL;
16140 fs_codec->error_handler = _Py_ERROR_UNKNOWN;
Victor Stinnerbf305cc2020-02-05 17:39:57 +010016141}
16142
16143
Victor Stinner709d23d2019-05-02 14:56:30 -040016144#ifdef MS_WINDOWS
16145int
16146_PyUnicode_EnableLegacyWindowsFSEncoding(void)
16147{
Victor Stinner81a7be32020-04-14 15:14:01 +020016148 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +020016149 PyConfig *config = (PyConfig *)_PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -040016150
16151 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
16152 wchar_t *encoding = _PyMem_RawWcsdup(L"mbcs");
16153 wchar_t *errors = _PyMem_RawWcsdup(L"replace");
16154 if (encoding == NULL || errors == NULL) {
16155 PyMem_RawFree(encoding);
16156 PyMem_RawFree(errors);
16157 PyErr_NoMemory();
16158 return -1;
16159 }
16160
16161 PyMem_RawFree(config->filesystem_encoding);
16162 config->filesystem_encoding = encoding;
16163 PyMem_RawFree(config->filesystem_errors);
16164 config->filesystem_errors = errors;
16165
16166 return init_fs_codec(interp);
16167}
16168#endif
16169
16170
Victor Stinnerfecc4f22019-03-19 14:20:29 +010016171void
Victor Stinner3d483342019-11-22 12:27:50 +010016172_PyUnicode_Fini(PyThreadState *tstate)
Victor Stinnerfecc4f22019-03-19 14:20:29 +010016173{
Victor Stinner3d483342019-11-22 12:27:50 +010016174 if (_Py_IsMainInterpreter(tstate)) {
Victor Stinnerfecc4f22019-03-19 14:20:29 +010016175#if defined(WITH_VALGRIND) || defined(__INSURE__)
Victor Stinner3d483342019-11-22 12:27:50 +010016176 /* Insure++ is a memory analysis tool that aids in discovering
16177 * memory leaks and other memory problems. On Python exit, the
16178 * interned string dictionaries are flagged as being in use at exit
16179 * (which it is). Under normal circumstances, this is fine because
16180 * the memory will be automatically reclaimed by the system. Under
16181 * memory debugging, it's a huge source of useless noise, so we
16182 * trade off slower shutdown for less distraction in the memory
16183 * reports. -baw
16184 */
16185 unicode_release_interned();
Victor Stinnerfecc4f22019-03-19 14:20:29 +010016186#endif /* __INSURE__ */
16187
Victor Stinner3d483342019-11-22 12:27:50 +010016188 Py_CLEAR(unicode_empty);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010016189
Victor Stinner607b1022020-05-05 18:50:30 +020016190#ifdef LATIN1_SINGLETONS
Victor Stinner3d483342019-11-22 12:27:50 +010016191 for (Py_ssize_t i = 0; i < 256; i++) {
16192 Py_CLEAR(unicode_latin1[i]);
16193 }
Victor Stinner607b1022020-05-05 18:50:30 +020016194#endif
Victor Stinnerd6fb53f2020-05-14 01:11:54 +020016195 unicode_clear_static_strings();
Victor Stinnerfecc4f22019-03-19 14:20:29 +010016196 }
Victor Stinner709d23d2019-05-02 14:56:30 -040016197
Victor Stinner3d17c042020-05-14 01:48:38 +020016198 _PyUnicode_FiniEncodings(&tstate->interp->unicode.fs_codec);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010016199}
16200
16201
Georg Brandl66c221e2010-10-14 07:04:07 +000016202/* A _string module, to export formatter_parser and formatter_field_name_split
16203 to the string.Formatter class implemented in Python. */
16204
16205static PyMethodDef _string_methods[] = {
16206 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
16207 METH_O, PyDoc_STR("split the argument as a field name")},
16208 {"formatter_parser", (PyCFunction) formatter_parser,
16209 METH_O, PyDoc_STR("parse the argument as a format string")},
16210 {NULL, NULL}
16211};
16212
16213static struct PyModuleDef _string_module = {
16214 PyModuleDef_HEAD_INIT,
16215 "_string",
16216 PyDoc_STR("string helper module"),
16217 0,
16218 _string_methods,
16219 NULL,
16220 NULL,
16221 NULL,
16222 NULL
16223};
16224
16225PyMODINIT_FUNC
16226PyInit__string(void)
16227{
16228 return PyModule_Create(&_string_module);
16229}
16230
16231
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000016232#ifdef __cplusplus
16233}
16234#endif