blob: 8ab3943e61b29f78d0bd5d9970dfcd17410cc2ba [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 Stinner9fc57a32018-11-07 00:44:03 +010043#include "pycore_fileutils.h"
Victor Stinnerbcda8f12018-11-21 22:27:47 +010044#include "pycore_object.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010045#include "pycore_pystate.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000046#include "ucnhash.h"
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050047#include "bytes_methods.h"
Raymond Hettingerac2ef652015-07-04 16:04:44 -070048#include "stringlib/eq.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000049
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000050#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000051#include <windows.h>
52#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000053
Victor Stinnerfecc4f22019-03-19 14:20:29 +010054/* Uncomment to display statistics on interned strings at exit when
55 using Valgrind or Insecure++. */
56/* #define INTERNED_STATS 1 */
57
58
Larry Hastings61272b72014-01-07 12:41:53 -080059/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090060class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080061[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090062/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
63
64/*[python input]
65class Py_UCS4_converter(CConverter):
66 type = 'Py_UCS4'
67 converter = 'convert_uc'
68
69 def converter_init(self):
70 if self.default is not unspecified:
71 self.c_default = ascii(self.default)
72 if len(self.c_default) > 4 or self.c_default[0] != "'":
73 self.c_default = hex(ord(self.default))
74
75[python start generated code]*/
76/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080077
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000078/* --- Globals ------------------------------------------------------------
79
Serhiy Storchaka05997252013-01-26 12:14:02 +020080NOTE: In the interpreter's initialization phase, some globals are currently
81 initialized dynamically as needed. In the process Unicode objects may
82 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000083
84*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000085
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000086
87#ifdef __cplusplus
88extern "C" {
89#endif
90
Victor Stinner8faf8212011-12-08 22:14:11 +010091/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
92#define MAX_UNICODE 0x10ffff
93
Victor Stinner910337b2011-10-03 03:20:16 +020094#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020095# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020096#else
97# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
98#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020099
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200100#define _PyUnicode_UTF8(op) \
101 (((PyCompactUnicodeObject*)(op))->utf8)
102#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200103 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200104 assert(PyUnicode_IS_READY(op)), \
105 PyUnicode_IS_COMPACT_ASCII(op) ? \
106 ((char*)((PyASCIIObject*)(op) + 1)) : \
107 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200108#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200109 (((PyCompactUnicodeObject*)(op))->utf8_length)
110#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200111 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200112 assert(PyUnicode_IS_READY(op)), \
113 PyUnicode_IS_COMPACT_ASCII(op) ? \
114 ((PyASCIIObject*)(op))->length : \
115 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200116#define _PyUnicode_WSTR(op) \
117 (((PyASCIIObject*)(op))->wstr)
118#define _PyUnicode_WSTR_LENGTH(op) \
119 (((PyCompactUnicodeObject*)(op))->wstr_length)
120#define _PyUnicode_LENGTH(op) \
121 (((PyASCIIObject *)(op))->length)
122#define _PyUnicode_STATE(op) \
123 (((PyASCIIObject *)(op))->state)
124#define _PyUnicode_HASH(op) \
125 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200126#define _PyUnicode_KIND(op) \
127 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200128 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200129#define _PyUnicode_GET_LENGTH(op) \
130 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200131 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200132#define _PyUnicode_DATA_ANY(op) \
133 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200134
Victor Stinner910337b2011-10-03 03:20:16 +0200135#undef PyUnicode_READY
136#define PyUnicode_READY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200139 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100140 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200141
Victor Stinnerc379ead2011-10-03 12:52:27 +0200142#define _PyUnicode_SHARE_UTF8(op) \
143 (assert(_PyUnicode_CHECK(op)), \
144 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
145 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
146#define _PyUnicode_SHARE_WSTR(op) \
147 (assert(_PyUnicode_CHECK(op)), \
148 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
149
Victor Stinner829c0ad2011-10-03 01:08:02 +0200150/* true if the Unicode object has an allocated UTF-8 memory block
151 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200152#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200153 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200154 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200155 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
156
Victor Stinner03490912011-10-03 23:45:12 +0200157/* true if the Unicode object has an allocated wstr memory block
158 (not shared with other data) */
159#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200160 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200161 (!PyUnicode_IS_READY(op) || \
162 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
163
Victor Stinner910337b2011-10-03 03:20:16 +0200164/* Generic helper macro to convert characters of different types.
165 from_type and to_type have to be valid type names, begin and end
166 are pointers to the source characters which should be of type
167 "from_type *". to is a pointer of type "to_type *" and points to the
168 buffer where the result characters are written to. */
169#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
170 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100171 to_type *_to = (to_type *)(to); \
172 const from_type *_iter = (from_type *)(begin); \
173 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200174 Py_ssize_t n = (_end) - (_iter); \
175 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200176 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200177 while (_iter < (_unrolled_end)) { \
178 _to[0] = (to_type) _iter[0]; \
179 _to[1] = (to_type) _iter[1]; \
180 _to[2] = (to_type) _iter[2]; \
181 _to[3] = (to_type) _iter[3]; \
182 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200183 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200184 while (_iter < (_end)) \
185 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200186 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200187
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200188#ifdef MS_WINDOWS
189 /* On Windows, overallocate by 50% is the best factor */
190# define OVERALLOCATE_FACTOR 2
191#else
192 /* On Linux, overallocate by 25% is the best factor */
193# define OVERALLOCATE_FACTOR 4
194#endif
195
Walter Dörwald16807132007-05-25 13:52:07 +0000196/* This dictionary holds all interned unicode strings. Note that references
197 to strings in this dictionary are *not* counted in the string's ob_refcnt.
198 When the interned string reaches a refcnt of 0 the string deallocation
199 function will delete the reference from this dictionary.
200
201 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000202 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000203*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200204static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000205
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000206/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200207static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200208
Serhiy Storchaka678db842013-01-26 12:16:36 +0200209#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200210 do { \
211 if (unicode_empty != NULL) \
212 Py_INCREF(unicode_empty); \
213 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200214 unicode_empty = PyUnicode_New(0, 0); \
215 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200216 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200217 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
218 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200219 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200220 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000221
Serhiy Storchaka678db842013-01-26 12:16:36 +0200222#define _Py_RETURN_UNICODE_EMPTY() \
223 do { \
224 _Py_INCREF_UNICODE_EMPTY(); \
225 return unicode_empty; \
226 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000227
Victor Stinner59423e32018-11-26 13:40:01 +0100228static inline void
229unicode_fill(enum PyUnicode_Kind kind, void *data, Py_UCS4 value,
230 Py_ssize_t start, Py_ssize_t length)
231{
232 assert(0 <= start);
233 assert(kind != PyUnicode_WCHAR_KIND);
234 switch (kind) {
235 case PyUnicode_1BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100236 assert(value <= 0xff);
Victor Stinner59423e32018-11-26 13:40:01 +0100237 Py_UCS1 ch = (unsigned char)value;
238 Py_UCS1 *to = (Py_UCS1 *)data + start;
239 memset(to, ch, length);
240 break;
241 }
242 case PyUnicode_2BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100243 assert(value <= 0xffff);
Victor Stinner59423e32018-11-26 13:40:01 +0100244 Py_UCS2 ch = (Py_UCS2)value;
245 Py_UCS2 *to = (Py_UCS2 *)data + start;
246 const Py_UCS2 *end = to + length;
247 for (; to < end; ++to) *to = ch;
248 break;
249 }
250 case PyUnicode_4BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100251 assert(value <= MAX_UNICODE);
Victor Stinner59423e32018-11-26 13:40:01 +0100252 Py_UCS4 ch = value;
253 Py_UCS4 * to = (Py_UCS4 *)data + start;
254 const Py_UCS4 *end = to + length;
255 for (; to < end; ++to) *to = ch;
256 break;
257 }
258 default: Py_UNREACHABLE();
259 }
260}
261
262
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200263/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700264static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200265_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
266
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200267/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200268static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200269
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000270/* Single character Unicode strings in the Latin-1 range are being
271 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200272static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000273
Christian Heimes190d79e2008-01-30 11:58:22 +0000274/* Fast detection of the most frequent whitespace characters */
275const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000276 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000277/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000278/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000279/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000280/* case 0x000C: * FORM FEED */
281/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 0, 1, 1, 1, 1, 1, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000284/* case 0x001C: * FILE SEPARATOR */
285/* case 0x001D: * GROUP SEPARATOR */
286/* case 0x001E: * RECORD SEPARATOR */
287/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000288 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000289/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000290 1, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0,
292 0, 0, 0, 0, 0, 0, 0, 0,
293 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000294
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0,
298 0, 0, 0, 0, 0, 0, 0, 0,
299 0, 0, 0, 0, 0, 0, 0, 0,
300 0, 0, 0, 0, 0, 0, 0, 0,
301 0, 0, 0, 0, 0, 0, 0, 0,
302 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000303};
304
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200305/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200306static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200307static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100308static int unicode_modifiable(PyObject *unicode);
309
Victor Stinnerfe226c02011-10-03 03:52:20 +0200310
Alexander Belopolsky40018472011-02-26 01:02:56 +0000311static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100312_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200313static PyObject *
314_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
315static PyObject *
316_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
317
318static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000319unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000320 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100321 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000322 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
323
Alexander Belopolsky40018472011-02-26 01:02:56 +0000324static void
325raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300326 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100327 PyObject *unicode,
328 Py_ssize_t startpos, Py_ssize_t endpos,
329 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000330
Christian Heimes190d79e2008-01-30 11:58:22 +0000331/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200332static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000333 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000334/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000335/* 0x000B, * LINE TABULATION */
336/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000337/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000338 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000339 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000340/* 0x001C, * FILE SEPARATOR */
341/* 0x001D, * GROUP SEPARATOR */
342/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000343 0, 0, 0, 0, 1, 1, 1, 0,
344 0, 0, 0, 0, 0, 0, 0, 0,
345 0, 0, 0, 0, 0, 0, 0, 0,
346 0, 0, 0, 0, 0, 0, 0, 0,
347 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000348
Benjamin Peterson14339b62009-01-31 16:36:08 +0000349 0, 0, 0, 0, 0, 0, 0, 0,
350 0, 0, 0, 0, 0, 0, 0, 0,
351 0, 0, 0, 0, 0, 0, 0, 0,
352 0, 0, 0, 0, 0, 0, 0, 0,
353 0, 0, 0, 0, 0, 0, 0, 0,
354 0, 0, 0, 0, 0, 0, 0, 0,
355 0, 0, 0, 0, 0, 0, 0, 0,
356 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000357};
358
INADA Naoki3ae20562017-01-16 20:41:20 +0900359static int convert_uc(PyObject *obj, void *addr);
360
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300361#include "clinic/unicodeobject.c.h"
362
Victor Stinner3d4226a2018-08-29 22:21:32 +0200363_Py_error_handler
364_Py_GetErrorHandler(const char *errors)
Victor Stinner50149202015-09-22 00:26:54 +0200365{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200366 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200367 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200368 }
369 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200370 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200371 }
372 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200373 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200374 }
375 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200376 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200377 }
378 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200379 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200380 }
381 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200382 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200383 }
384 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200385 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200386 }
Victor Stinner50149202015-09-22 00:26:54 +0200387 return _Py_ERROR_OTHER;
388}
389
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300390/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
391 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000392Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000393PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000394{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000395#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000396 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000397#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000398 /* This is actually an illegal character, so it should
399 not be passed to unichr. */
400 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000401#endif
402}
403
Victor Stinner910337b2011-10-03 03:20:16 +0200404#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200405int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100406_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200407{
Victor Stinner50fe3f82018-10-26 18:47:15 +0200408#define ASSERT(expr) _PyObject_ASSERT(op, (expr))
409
Victor Stinner910337b2011-10-03 03:20:16 +0200410 PyASCIIObject *ascii;
411 unsigned int kind;
412
Victor Stinner50fe3f82018-10-26 18:47:15 +0200413 ASSERT(PyUnicode_Check(op));
Victor Stinner910337b2011-10-03 03:20:16 +0200414
415 ascii = (PyASCIIObject *)op;
416 kind = ascii->state.kind;
417
Victor Stinnera3b334d2011-10-03 13:53:37 +0200418 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200419 ASSERT(kind == PyUnicode_1BYTE_KIND);
420 ASSERT(ascii->state.ready == 1);
Victor Stinner910337b2011-10-03 03:20:16 +0200421 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200422 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200423 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200424 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200425
Victor Stinnera41463c2011-10-04 01:05:08 +0200426 if (ascii->state.compact == 1) {
427 data = compact + 1;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200428 ASSERT(kind == PyUnicode_1BYTE_KIND
Victor Stinner910337b2011-10-03 03:20:16 +0200429 || kind == PyUnicode_2BYTE_KIND
430 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200431 ASSERT(ascii->state.ascii == 0);
432 ASSERT(ascii->state.ready == 1);
433 ASSERT (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100434 }
435 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200436 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
437
438 data = unicode->data.any;
439 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200440 ASSERT(ascii->length == 0);
441 ASSERT(ascii->hash == -1);
442 ASSERT(ascii->state.compact == 0);
443 ASSERT(ascii->state.ascii == 0);
444 ASSERT(ascii->state.ready == 0);
445 ASSERT(ascii->state.interned == SSTATE_NOT_INTERNED);
446 ASSERT(ascii->wstr != NULL);
447 ASSERT(data == NULL);
448 ASSERT(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200449 }
450 else {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200451 ASSERT(kind == PyUnicode_1BYTE_KIND
Victor Stinnera41463c2011-10-04 01:05:08 +0200452 || kind == PyUnicode_2BYTE_KIND
453 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200454 ASSERT(ascii->state.compact == 0);
455 ASSERT(ascii->state.ready == 1);
456 ASSERT(data != NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200457 if (ascii->state.ascii) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200458 ASSERT (compact->utf8 == data);
459 ASSERT (compact->utf8_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200460 }
461 else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200462 ASSERT (compact->utf8 != data);
Victor Stinnera41463c2011-10-04 01:05:08 +0200463 }
464 }
465 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200466 if (
467#if SIZEOF_WCHAR_T == 2
468 kind == PyUnicode_2BYTE_KIND
469#else
470 kind == PyUnicode_4BYTE_KIND
471#endif
472 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200473 {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200474 ASSERT(ascii->wstr == data);
475 ASSERT(compact->wstr_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200476 } else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200477 ASSERT(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200478 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200479
480 if (compact->utf8 == NULL)
Victor Stinner50fe3f82018-10-26 18:47:15 +0200481 ASSERT(compact->utf8_length == 0);
Victor Stinnera41463c2011-10-04 01:05:08 +0200482 if (ascii->wstr == NULL)
Victor Stinner50fe3f82018-10-26 18:47:15 +0200483 ASSERT(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200484 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200485 /* check that the best kind is used */
486 if (check_content && kind != PyUnicode_WCHAR_KIND)
487 {
488 Py_ssize_t i;
489 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200490 void *data;
491 Py_UCS4 ch;
492
493 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200494 for (i=0; i < ascii->length; i++)
495 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200496 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200497 if (ch > maxchar)
498 maxchar = ch;
499 }
500 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100501 if (ascii->state.ascii == 0) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200502 ASSERT(maxchar >= 128);
503 ASSERT(maxchar <= 255);
Victor Stinner77faf692011-11-20 18:56:05 +0100504 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200505 else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200506 ASSERT(maxchar < 128);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200507 }
Victor Stinner77faf692011-11-20 18:56:05 +0100508 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200509 ASSERT(maxchar >= 0x100);
510 ASSERT(maxchar <= 0xFFFF);
Victor Stinner77faf692011-11-20 18:56:05 +0100511 }
512 else {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200513 ASSERT(maxchar >= 0x10000);
514 ASSERT(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100515 }
Victor Stinner50fe3f82018-10-26 18:47:15 +0200516 ASSERT(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200517 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400518 return 1;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200519
520#undef ASSERT
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400521}
Victor Stinner910337b2011-10-03 03:20:16 +0200522#endif
523
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100524static PyObject*
525unicode_result_wchar(PyObject *unicode)
526{
527#ifndef Py_DEBUG
528 Py_ssize_t len;
529
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100530 len = _PyUnicode_WSTR_LENGTH(unicode);
531 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100532 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200533 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100534 }
535
536 if (len == 1) {
537 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100538 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100539 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
540 Py_DECREF(unicode);
541 return latin1_char;
542 }
543 }
544
545 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200546 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100547 return NULL;
548 }
549#else
Victor Stinneraa771272012-10-04 02:32:58 +0200550 assert(Py_REFCNT(unicode) == 1);
551
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100552 /* don't make the result ready in debug mode to ensure that the caller
553 makes the string ready before using it */
554 assert(_PyUnicode_CheckConsistency(unicode, 1));
555#endif
556 return unicode;
557}
558
559static PyObject*
560unicode_result_ready(PyObject *unicode)
561{
562 Py_ssize_t length;
563
564 length = PyUnicode_GET_LENGTH(unicode);
565 if (length == 0) {
566 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100567 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200568 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100569 }
570 return unicode_empty;
571 }
572
573 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200574 void *data = PyUnicode_DATA(unicode);
575 int kind = PyUnicode_KIND(unicode);
576 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100577 if (ch < 256) {
578 PyObject *latin1_char = unicode_latin1[ch];
579 if (latin1_char != NULL) {
580 if (unicode != latin1_char) {
581 Py_INCREF(latin1_char);
582 Py_DECREF(unicode);
583 }
584 return latin1_char;
585 }
586 else {
587 assert(_PyUnicode_CheckConsistency(unicode, 1));
588 Py_INCREF(unicode);
589 unicode_latin1[ch] = unicode;
590 return unicode;
591 }
592 }
593 }
594
595 assert(_PyUnicode_CheckConsistency(unicode, 1));
596 return unicode;
597}
598
599static PyObject*
600unicode_result(PyObject *unicode)
601{
602 assert(_PyUnicode_CHECK(unicode));
603 if (PyUnicode_IS_READY(unicode))
604 return unicode_result_ready(unicode);
605 else
606 return unicode_result_wchar(unicode);
607}
608
Victor Stinnerc4b49542011-12-11 22:44:26 +0100609static PyObject*
610unicode_result_unchanged(PyObject *unicode)
611{
612 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500613 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100614 return NULL;
615 Py_INCREF(unicode);
616 return unicode;
617 }
618 else
619 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100620 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100621}
622
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200623/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
624 ASCII, Latin1, UTF-8, etc. */
625static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200626backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200627 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
628{
Victor Stinnerad771582015-10-09 12:38:53 +0200629 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200630 Py_UCS4 ch;
631 enum PyUnicode_Kind kind;
632 void *data;
633
634 assert(PyUnicode_IS_READY(unicode));
635 kind = PyUnicode_KIND(unicode);
636 data = PyUnicode_DATA(unicode);
637
638 size = 0;
639 /* determine replacement size */
640 for (i = collstart; i < collend; ++i) {
641 Py_ssize_t incr;
642
643 ch = PyUnicode_READ(kind, data, i);
644 if (ch < 0x100)
645 incr = 2+2;
646 else if (ch < 0x10000)
647 incr = 2+4;
648 else {
649 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200650 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200651 }
652 if (size > PY_SSIZE_T_MAX - incr) {
653 PyErr_SetString(PyExc_OverflowError,
654 "encoded result is too long for a Python string");
655 return NULL;
656 }
657 size += incr;
658 }
659
Victor Stinnerad771582015-10-09 12:38:53 +0200660 str = _PyBytesWriter_Prepare(writer, str, size);
661 if (str == NULL)
662 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200663
664 /* generate replacement */
665 for (i = collstart; i < collend; ++i) {
666 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200667 *str++ = '\\';
668 if (ch >= 0x00010000) {
669 *str++ = 'U';
670 *str++ = Py_hexdigits[(ch>>28)&0xf];
671 *str++ = Py_hexdigits[(ch>>24)&0xf];
672 *str++ = Py_hexdigits[(ch>>20)&0xf];
673 *str++ = Py_hexdigits[(ch>>16)&0xf];
674 *str++ = Py_hexdigits[(ch>>12)&0xf];
675 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200676 }
Victor Stinner797485e2015-10-09 03:17:30 +0200677 else if (ch >= 0x100) {
678 *str++ = 'u';
679 *str++ = Py_hexdigits[(ch>>12)&0xf];
680 *str++ = Py_hexdigits[(ch>>8)&0xf];
681 }
682 else
683 *str++ = 'x';
684 *str++ = Py_hexdigits[(ch>>4)&0xf];
685 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200686 }
687 return str;
688}
689
690/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
691 ASCII, Latin1, UTF-8, etc. */
692static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200693xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200694 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
695{
Victor Stinnerad771582015-10-09 12:38:53 +0200696 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200697 Py_UCS4 ch;
698 enum PyUnicode_Kind kind;
699 void *data;
700
701 assert(PyUnicode_IS_READY(unicode));
702 kind = PyUnicode_KIND(unicode);
703 data = PyUnicode_DATA(unicode);
704
705 size = 0;
706 /* determine replacement size */
707 for (i = collstart; i < collend; ++i) {
708 Py_ssize_t incr;
709
710 ch = PyUnicode_READ(kind, data, i);
711 if (ch < 10)
712 incr = 2+1+1;
713 else if (ch < 100)
714 incr = 2+2+1;
715 else if (ch < 1000)
716 incr = 2+3+1;
717 else if (ch < 10000)
718 incr = 2+4+1;
719 else if (ch < 100000)
720 incr = 2+5+1;
721 else if (ch < 1000000)
722 incr = 2+6+1;
723 else {
724 assert(ch <= MAX_UNICODE);
725 incr = 2+7+1;
726 }
727 if (size > PY_SSIZE_T_MAX - incr) {
728 PyErr_SetString(PyExc_OverflowError,
729 "encoded result is too long for a Python string");
730 return NULL;
731 }
732 size += incr;
733 }
734
Victor Stinnerad771582015-10-09 12:38:53 +0200735 str = _PyBytesWriter_Prepare(writer, str, size);
736 if (str == NULL)
737 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200738
739 /* generate replacement */
740 for (i = collstart; i < collend; ++i) {
741 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
742 }
743 return str;
744}
745
Thomas Wouters477c8d52006-05-27 19:21:47 +0000746/* --- Bloom Filters ----------------------------------------------------- */
747
748/* stuff to implement simple "bloom filters" for Unicode characters.
749 to keep things simple, we use a single bitmask, using the least 5
750 bits from each unicode characters as the bit index. */
751
752/* the linebreak mask is set up by Unicode_Init below */
753
Antoine Pitrouf068f942010-01-13 14:19:12 +0000754#if LONG_BIT >= 128
755#define BLOOM_WIDTH 128
756#elif LONG_BIT >= 64
757#define BLOOM_WIDTH 64
758#elif LONG_BIT >= 32
759#define BLOOM_WIDTH 32
760#else
761#error "LONG_BIT is smaller than 32"
762#endif
763
Thomas Wouters477c8d52006-05-27 19:21:47 +0000764#define BLOOM_MASK unsigned long
765
Serhiy Storchaka05997252013-01-26 12:14:02 +0200766static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000767
Antoine Pitrouf068f942010-01-13 14:19:12 +0000768#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000769
Benjamin Peterson29060642009-01-31 22:14:21 +0000770#define BLOOM_LINEBREAK(ch) \
771 ((ch) < 128U ? ascii_linebreak[(ch)] : \
772 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000773
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700774static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200775make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776{
Victor Stinnera85af502013-04-09 21:53:54 +0200777#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
778 do { \
779 TYPE *data = (TYPE *)PTR; \
780 TYPE *end = data + LEN; \
781 Py_UCS4 ch; \
782 for (; data != end; data++) { \
783 ch = *data; \
784 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
785 } \
786 break; \
787 } while (0)
788
Thomas Wouters477c8d52006-05-27 19:21:47 +0000789 /* calculate simple bloom-style bitmask for a given unicode string */
790
Antoine Pitrouf068f942010-01-13 14:19:12 +0000791 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000792
793 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200794 switch (kind) {
795 case PyUnicode_1BYTE_KIND:
796 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
797 break;
798 case PyUnicode_2BYTE_KIND:
799 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
800 break;
801 case PyUnicode_4BYTE_KIND:
802 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
803 break;
804 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700805 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200806 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000807 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200808
809#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810}
811
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300812static int
813ensure_unicode(PyObject *obj)
814{
815 if (!PyUnicode_Check(obj)) {
816 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +0200817 "must be str, not %.100s",
818 Py_TYPE(obj)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300819 return -1;
820 }
821 return PyUnicode_READY(obj);
822}
823
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200824/* Compilation of templated routines */
825
826#include "stringlib/asciilib.h"
827#include "stringlib/fastsearch.h"
828#include "stringlib/partition.h"
829#include "stringlib/split.h"
830#include "stringlib/count.h"
831#include "stringlib/find.h"
832#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200833#include "stringlib/undef.h"
834
835#include "stringlib/ucs1lib.h"
836#include "stringlib/fastsearch.h"
837#include "stringlib/partition.h"
838#include "stringlib/split.h"
839#include "stringlib/count.h"
840#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300841#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200842#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200843#include "stringlib/undef.h"
844
845#include "stringlib/ucs2lib.h"
846#include "stringlib/fastsearch.h"
847#include "stringlib/partition.h"
848#include "stringlib/split.h"
849#include "stringlib/count.h"
850#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300851#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200852#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200853#include "stringlib/undef.h"
854
855#include "stringlib/ucs4lib.h"
856#include "stringlib/fastsearch.h"
857#include "stringlib/partition.h"
858#include "stringlib/split.h"
859#include "stringlib/count.h"
860#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300861#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200862#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200863#include "stringlib/undef.h"
864
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200865#include "stringlib/unicodedefs.h"
866#include "stringlib/fastsearch.h"
867#include "stringlib/count.h"
868#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100869#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200870
Guido van Rossumd57fd912000-03-10 22:53:23 +0000871/* --- Unicode Object ----------------------------------------------------- */
872
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700873static inline Py_ssize_t
874findchar(const void *s, int kind,
875 Py_ssize_t size, Py_UCS4 ch,
876 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200878 switch (kind) {
879 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200880 if ((Py_UCS1) ch != ch)
881 return -1;
882 if (direction > 0)
883 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
884 else
885 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200886 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200887 if ((Py_UCS2) ch != ch)
888 return -1;
889 if (direction > 0)
890 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
891 else
892 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200893 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200894 if (direction > 0)
895 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
896 else
897 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200898 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700899 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200900 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200901}
902
Victor Stinnerafffce42012-10-03 23:03:17 +0200903#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000904/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200905 earlier.
906
907 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
908 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
909 invalid character in Unicode 6.0. */
910static void
911unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
912{
913 int kind = PyUnicode_KIND(unicode);
914 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
915 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
916 if (length <= old_length)
917 return;
918 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
919}
920#endif
921
Victor Stinnerfe226c02011-10-03 03:52:20 +0200922static PyObject*
923resize_compact(PyObject *unicode, Py_ssize_t length)
924{
925 Py_ssize_t char_size;
926 Py_ssize_t struct_size;
927 Py_ssize_t new_size;
928 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100929 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200930#ifdef Py_DEBUG
931 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
932#endif
933
Victor Stinner79891572012-05-03 13:43:07 +0200934 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200935 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100936 assert(PyUnicode_IS_COMPACT(unicode));
937
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200938 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100939 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 struct_size = sizeof(PyASCIIObject);
941 else
942 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200943 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200944
Victor Stinnerfe226c02011-10-03 03:52:20 +0200945 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
946 PyErr_NoMemory();
947 return NULL;
948 }
949 new_size = (struct_size + (length + 1) * char_size);
950
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200951 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
952 PyObject_DEL(_PyUnicode_UTF8(unicode));
953 _PyUnicode_UTF8(unicode) = NULL;
954 _PyUnicode_UTF8_LENGTH(unicode) = 0;
955 }
Victor Stinner84def372011-12-11 20:04:56 +0100956 _Py_DEC_REFTOTAL;
957 _Py_ForgetReference(unicode);
958
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300959 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100960 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100961 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200962 PyErr_NoMemory();
963 return NULL;
964 }
Victor Stinner84def372011-12-11 20:04:56 +0100965 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200966 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100967
Victor Stinnerfe226c02011-10-03 03:52:20 +0200968 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200969 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200970 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100971 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200972 _PyUnicode_WSTR_LENGTH(unicode) = length;
973 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100974 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
975 PyObject_DEL(_PyUnicode_WSTR(unicode));
976 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100977 if (!PyUnicode_IS_ASCII(unicode))
978 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100979 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200980#ifdef Py_DEBUG
981 unicode_fill_invalid(unicode, old_length);
982#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200983 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
984 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200985 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200986 return unicode;
987}
988
Alexander Belopolsky40018472011-02-26 01:02:56 +0000989static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200990resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000991{
Victor Stinner95663112011-10-04 01:03:50 +0200992 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100993 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200994 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200995 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000996
Victor Stinnerfe226c02011-10-03 03:52:20 +0200997 if (PyUnicode_IS_READY(unicode)) {
998 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200999 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001000 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +02001001#ifdef Py_DEBUG
1002 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
1003#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001004
1005 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001006 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +02001007 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
1008 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001009
1010 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1011 PyErr_NoMemory();
1012 return -1;
1013 }
1014 new_size = (length + 1) * char_size;
1015
Victor Stinner7a9105a2011-12-12 00:13:42 +01001016 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1017 {
1018 PyObject_DEL(_PyUnicode_UTF8(unicode));
1019 _PyUnicode_UTF8(unicode) = NULL;
1020 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1021 }
1022
Victor Stinnerfe226c02011-10-03 03:52:20 +02001023 data = (PyObject *)PyObject_REALLOC(data, new_size);
1024 if (data == NULL) {
1025 PyErr_NoMemory();
1026 return -1;
1027 }
1028 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001029 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001030 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001031 _PyUnicode_WSTR_LENGTH(unicode) = length;
1032 }
1033 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001034 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001035 _PyUnicode_UTF8_LENGTH(unicode) = length;
1036 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001037 _PyUnicode_LENGTH(unicode) = length;
1038 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001039#ifdef Py_DEBUG
1040 unicode_fill_invalid(unicode, old_length);
1041#endif
Victor Stinner95663112011-10-04 01:03:50 +02001042 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001043 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001044 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001045 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001046 }
Victor Stinner95663112011-10-04 01:03:50 +02001047 assert(_PyUnicode_WSTR(unicode) != NULL);
1048
1049 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001050 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001051 PyErr_NoMemory();
1052 return -1;
1053 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001054 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001055 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001056 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001057 if (!wstr) {
1058 PyErr_NoMemory();
1059 return -1;
1060 }
1061 _PyUnicode_WSTR(unicode) = wstr;
1062 _PyUnicode_WSTR(unicode)[length] = 0;
1063 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001064 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001065 return 0;
1066}
1067
Victor Stinnerfe226c02011-10-03 03:52:20 +02001068static PyObject*
1069resize_copy(PyObject *unicode, Py_ssize_t length)
1070{
1071 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001072 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001073 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001074
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001075 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001076
1077 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1078 if (copy == NULL)
1079 return NULL;
1080
1081 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001082 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001083 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001084 }
1085 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001086 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001087
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001088 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001089 if (w == NULL)
1090 return NULL;
1091 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1092 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001093 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001094 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001095 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001096 }
1097}
1098
Guido van Rossumd57fd912000-03-10 22:53:23 +00001099/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001100 Ux0000 terminated; some code (e.g. new_identifier)
1101 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001102
1103 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001104 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001105
1106*/
1107
Alexander Belopolsky40018472011-02-26 01:02:56 +00001108static PyUnicodeObject *
1109_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001110{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001111 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001112 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001113
Thomas Wouters477c8d52006-05-27 19:21:47 +00001114 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001115 if (length == 0 && unicode_empty != NULL) {
1116 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001117 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001118 }
1119
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001120 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001121 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001122 return (PyUnicodeObject *)PyErr_NoMemory();
1123 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001124 if (length < 0) {
1125 PyErr_SetString(PyExc_SystemError,
1126 "Negative size passed to _PyUnicode_New");
1127 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001128 }
1129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001130 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1131 if (unicode == NULL)
1132 return NULL;
1133 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001134
1135 _PyUnicode_WSTR_LENGTH(unicode) = length;
1136 _PyUnicode_HASH(unicode) = -1;
1137 _PyUnicode_STATE(unicode).interned = 0;
1138 _PyUnicode_STATE(unicode).kind = 0;
1139 _PyUnicode_STATE(unicode).compact = 0;
1140 _PyUnicode_STATE(unicode).ready = 0;
1141 _PyUnicode_STATE(unicode).ascii = 0;
1142 _PyUnicode_DATA_ANY(unicode) = NULL;
1143 _PyUnicode_LENGTH(unicode) = 0;
1144 _PyUnicode_UTF8(unicode) = NULL;
1145 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001147 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1148 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001149 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001150 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001151 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001152 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001153
Jeremy Hyltond8082792003-09-16 19:41:39 +00001154 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001155 * the caller fails before initializing str -- unicode_resize()
1156 * reads str[0], and the Keep-Alive optimization can keep memory
1157 * allocated for str alive across a call to unicode_dealloc(unicode).
1158 * We don't want unicode_resize to read uninitialized memory in
1159 * that case.
1160 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001161 _PyUnicode_WSTR(unicode)[0] = 0;
1162 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001163
Victor Stinner7931d9a2011-11-04 00:22:48 +01001164 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001165 return unicode;
1166}
1167
Victor Stinnerf42dc442011-10-02 23:33:16 +02001168static const char*
1169unicode_kind_name(PyObject *unicode)
1170{
Victor Stinner42dfd712011-10-03 14:41:45 +02001171 /* don't check consistency: unicode_kind_name() is called from
1172 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001173 if (!PyUnicode_IS_COMPACT(unicode))
1174 {
1175 if (!PyUnicode_IS_READY(unicode))
1176 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001177 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001178 {
1179 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001180 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001181 return "legacy ascii";
1182 else
1183 return "legacy latin1";
1184 case PyUnicode_2BYTE_KIND:
1185 return "legacy UCS2";
1186 case PyUnicode_4BYTE_KIND:
1187 return "legacy UCS4";
1188 default:
1189 return "<legacy invalid kind>";
1190 }
1191 }
1192 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001193 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001194 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001195 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001196 return "ascii";
1197 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001198 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001199 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001200 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001201 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001202 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001203 default:
1204 return "<invalid compact kind>";
1205 }
1206}
1207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209/* Functions wrapping macros for use in debugger */
Victor Stinnera42de742018-11-22 10:25:22 +01001210char *_PyUnicode_utf8(void *unicode_raw){
1211 PyObject *unicode = _PyObject_CAST(unicode_raw);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001212 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001213}
1214
Victor Stinnera42de742018-11-22 10:25:22 +01001215void *_PyUnicode_compact_data(void *unicode_raw) {
1216 PyObject *unicode = _PyObject_CAST(unicode_raw);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001217 return _PyUnicode_COMPACT_DATA(unicode);
1218}
Victor Stinnera42de742018-11-22 10:25:22 +01001219void *_PyUnicode_data(void *unicode_raw) {
1220 PyObject *unicode = _PyObject_CAST(unicode_raw);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001221 printf("obj %p\n", unicode);
1222 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1223 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1224 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1225 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1226 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1227 return PyUnicode_DATA(unicode);
1228}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001229
1230void
1231_PyUnicode_Dump(PyObject *op)
1232{
1233 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001234 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1235 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1236 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001237
Victor Stinnera849a4b2011-10-03 12:12:11 +02001238 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001239 {
1240 if (ascii->state.ascii)
1241 data = (ascii + 1);
1242 else
1243 data = (compact + 1);
1244 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001245 else
1246 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001247 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1248 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001249
Victor Stinnera849a4b2011-10-03 12:12:11 +02001250 if (ascii->wstr == data)
1251 printf("shared ");
1252 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001253
Victor Stinnera3b334d2011-10-03 13:53:37 +02001254 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001255 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001256 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1257 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001258 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1259 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001260 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001261 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001262}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263#endif
1264
1265PyObject *
1266PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1267{
1268 PyObject *obj;
1269 PyCompactUnicodeObject *unicode;
1270 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001271 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001272 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001273 Py_ssize_t char_size;
1274 Py_ssize_t struct_size;
1275
1276 /* Optimization for empty strings */
1277 if (size == 0 && unicode_empty != NULL) {
1278 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001279 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001280 }
1281
Victor Stinner9e9d6892011-10-04 01:02:02 +02001282 is_ascii = 0;
1283 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001284 struct_size = sizeof(PyCompactUnicodeObject);
1285 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001286 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001287 char_size = 1;
1288 is_ascii = 1;
1289 struct_size = sizeof(PyASCIIObject);
1290 }
1291 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001292 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001293 char_size = 1;
1294 }
1295 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001296 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001297 char_size = 2;
1298 if (sizeof(wchar_t) == 2)
1299 is_sharing = 1;
1300 }
1301 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001302 if (maxchar > MAX_UNICODE) {
1303 PyErr_SetString(PyExc_SystemError,
1304 "invalid maximum character passed to PyUnicode_New");
1305 return NULL;
1306 }
Victor Stinner8f825062012-04-27 13:55:39 +02001307 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001308 char_size = 4;
1309 if (sizeof(wchar_t) == 4)
1310 is_sharing = 1;
1311 }
1312
1313 /* Ensure we won't overflow the size. */
1314 if (size < 0) {
1315 PyErr_SetString(PyExc_SystemError,
1316 "Negative size passed to PyUnicode_New");
1317 return NULL;
1318 }
1319 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1320 return PyErr_NoMemory();
1321
1322 /* Duplicated allocation code from _PyObject_New() instead of a call to
1323 * PyObject_New() so we are able to allocate space for the object and
1324 * it's data buffer.
1325 */
1326 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1327 if (obj == NULL)
1328 return PyErr_NoMemory();
1329 obj = PyObject_INIT(obj, &PyUnicode_Type);
1330 if (obj == NULL)
1331 return NULL;
1332
1333 unicode = (PyCompactUnicodeObject *)obj;
1334 if (is_ascii)
1335 data = ((PyASCIIObject*)obj) + 1;
1336 else
1337 data = unicode + 1;
1338 _PyUnicode_LENGTH(unicode) = size;
1339 _PyUnicode_HASH(unicode) = -1;
1340 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001341 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 _PyUnicode_STATE(unicode).compact = 1;
1343 _PyUnicode_STATE(unicode).ready = 1;
1344 _PyUnicode_STATE(unicode).ascii = is_ascii;
1345 if (is_ascii) {
1346 ((char*)data)[size] = 0;
1347 _PyUnicode_WSTR(unicode) = NULL;
1348 }
Victor Stinner8f825062012-04-27 13:55:39 +02001349 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001350 ((char*)data)[size] = 0;
1351 _PyUnicode_WSTR(unicode) = NULL;
1352 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001353 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001354 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001355 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001356 else {
1357 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001358 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001359 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001360 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001361 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 ((Py_UCS4*)data)[size] = 0;
1363 if (is_sharing) {
1364 _PyUnicode_WSTR_LENGTH(unicode) = size;
1365 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1366 }
1367 else {
1368 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1369 _PyUnicode_WSTR(unicode) = NULL;
1370 }
1371 }
Victor Stinner8f825062012-04-27 13:55:39 +02001372#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001373 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001374#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001375 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376 return obj;
1377}
1378
1379#if SIZEOF_WCHAR_T == 2
1380/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1381 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001382 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001383
1384 This function assumes that unicode can hold one more code point than wstr
1385 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001386static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001388 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389{
1390 const wchar_t *iter;
1391 Py_UCS4 *ucs4_out;
1392
Victor Stinner910337b2011-10-03 03:20:16 +02001393 assert(unicode != NULL);
1394 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001395 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1396 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1397
1398 for (iter = begin; iter < end; ) {
1399 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1400 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001401 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1402 && (iter+1) < end
1403 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404 {
Victor Stinner551ac952011-11-29 22:58:13 +01001405 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 iter += 2;
1407 }
1408 else {
1409 *ucs4_out++ = *iter;
1410 iter++;
1411 }
1412 }
1413 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1414 _PyUnicode_GET_LENGTH(unicode)));
1415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416}
1417#endif
1418
Victor Stinnercd9950f2011-10-02 00:34:53 +02001419static int
Victor Stinner488fa492011-12-12 00:01:39 +01001420unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001421{
Victor Stinner488fa492011-12-12 00:01:39 +01001422 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001423 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001424 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001425 return -1;
1426 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001427 return 0;
1428}
1429
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001430static int
1431_copy_characters(PyObject *to, Py_ssize_t to_start,
1432 PyObject *from, Py_ssize_t from_start,
1433 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001434{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001435 unsigned int from_kind, to_kind;
1436 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001437
Victor Stinneree4544c2012-05-09 22:24:08 +02001438 assert(0 <= how_many);
1439 assert(0 <= from_start);
1440 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001441 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001442 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001443 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001444
Victor Stinnerd3f08822012-05-29 12:57:52 +02001445 assert(PyUnicode_Check(to));
1446 assert(PyUnicode_IS_READY(to));
1447 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1448
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001449 if (how_many == 0)
1450 return 0;
1451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001452 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001453 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001454 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001455 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456
Victor Stinnerf1852262012-06-16 16:38:26 +02001457#ifdef Py_DEBUG
1458 if (!check_maxchar
1459 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1460 {
1461 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1462 Py_UCS4 ch;
1463 Py_ssize_t i;
1464 for (i=0; i < how_many; i++) {
1465 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1466 assert(ch <= to_maxchar);
1467 }
1468 }
1469#endif
1470
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001471 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001472 if (check_maxchar
1473 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1474 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001475 /* Writing Latin-1 characters into an ASCII string requires to
1476 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001477 Py_UCS4 max_char;
1478 max_char = ucs1lib_find_max_char(from_data,
1479 (Py_UCS1*)from_data + how_many);
1480 if (max_char >= 128)
1481 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001482 }
Christian Heimesf051e432016-09-13 20:22:02 +02001483 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001484 (char*)from_data + from_kind * from_start,
1485 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001486 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001487 else if (from_kind == PyUnicode_1BYTE_KIND
1488 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001489 {
1490 _PyUnicode_CONVERT_BYTES(
1491 Py_UCS1, Py_UCS2,
1492 PyUnicode_1BYTE_DATA(from) + from_start,
1493 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1494 PyUnicode_2BYTE_DATA(to) + to_start
1495 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001496 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001497 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001498 && to_kind == PyUnicode_4BYTE_KIND)
1499 {
1500 _PyUnicode_CONVERT_BYTES(
1501 Py_UCS1, Py_UCS4,
1502 PyUnicode_1BYTE_DATA(from) + from_start,
1503 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1504 PyUnicode_4BYTE_DATA(to) + to_start
1505 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001506 }
1507 else if (from_kind == PyUnicode_2BYTE_KIND
1508 && to_kind == PyUnicode_4BYTE_KIND)
1509 {
1510 _PyUnicode_CONVERT_BYTES(
1511 Py_UCS2, Py_UCS4,
1512 PyUnicode_2BYTE_DATA(from) + from_start,
1513 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1514 PyUnicode_4BYTE_DATA(to) + to_start
1515 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001516 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001517 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001518 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1519
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001520 if (!check_maxchar) {
1521 if (from_kind == PyUnicode_2BYTE_KIND
1522 && to_kind == PyUnicode_1BYTE_KIND)
1523 {
1524 _PyUnicode_CONVERT_BYTES(
1525 Py_UCS2, Py_UCS1,
1526 PyUnicode_2BYTE_DATA(from) + from_start,
1527 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1528 PyUnicode_1BYTE_DATA(to) + to_start
1529 );
1530 }
1531 else if (from_kind == PyUnicode_4BYTE_KIND
1532 && to_kind == PyUnicode_1BYTE_KIND)
1533 {
1534 _PyUnicode_CONVERT_BYTES(
1535 Py_UCS4, Py_UCS1,
1536 PyUnicode_4BYTE_DATA(from) + from_start,
1537 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1538 PyUnicode_1BYTE_DATA(to) + to_start
1539 );
1540 }
1541 else if (from_kind == PyUnicode_4BYTE_KIND
1542 && to_kind == PyUnicode_2BYTE_KIND)
1543 {
1544 _PyUnicode_CONVERT_BYTES(
1545 Py_UCS4, Py_UCS2,
1546 PyUnicode_4BYTE_DATA(from) + from_start,
1547 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1548 PyUnicode_2BYTE_DATA(to) + to_start
1549 );
1550 }
1551 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001552 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001553 }
1554 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001555 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001556 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001557 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001558 Py_ssize_t i;
1559
Victor Stinnera0702ab2011-09-29 14:14:38 +02001560 for (i=0; i < how_many; i++) {
1561 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001562 if (ch > to_maxchar)
1563 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001564 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1565 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001566 }
1567 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001568 return 0;
1569}
1570
Victor Stinnerd3f08822012-05-29 12:57:52 +02001571void
1572_PyUnicode_FastCopyCharacters(
1573 PyObject *to, Py_ssize_t to_start,
1574 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001575{
1576 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1577}
1578
1579Py_ssize_t
1580PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1581 PyObject *from, Py_ssize_t from_start,
1582 Py_ssize_t how_many)
1583{
1584 int err;
1585
1586 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1587 PyErr_BadInternalCall();
1588 return -1;
1589 }
1590
Benjamin Petersonbac79492012-01-14 13:34:47 -05001591 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001592 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001593 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001594 return -1;
1595
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001596 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001597 PyErr_SetString(PyExc_IndexError, "string index out of range");
1598 return -1;
1599 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001600 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001601 PyErr_SetString(PyExc_IndexError, "string index out of range");
1602 return -1;
1603 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001604 if (how_many < 0) {
1605 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1606 return -1;
1607 }
1608 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001609 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1610 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001611 "Cannot write %zi characters at %zi "
1612 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001613 how_many, to_start, PyUnicode_GET_LENGTH(to));
1614 return -1;
1615 }
1616
1617 if (how_many == 0)
1618 return 0;
1619
Victor Stinner488fa492011-12-12 00:01:39 +01001620 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001621 return -1;
1622
1623 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1624 if (err) {
1625 PyErr_Format(PyExc_SystemError,
1626 "Cannot copy %s characters "
1627 "into a string of %s characters",
1628 unicode_kind_name(from),
1629 unicode_kind_name(to));
1630 return -1;
1631 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001632 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001633}
1634
Victor Stinner17222162011-09-28 22:15:37 +02001635/* Find the maximum code point and count the number of surrogate pairs so a
1636 correct string length can be computed before converting a string to UCS4.
1637 This function counts single surrogates as a character and not as a pair.
1638
1639 Return 0 on success, or -1 on error. */
1640static int
1641find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1642 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643{
1644 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001645 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001646
Victor Stinnerc53be962011-10-02 21:33:54 +02001647 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001648 *num_surrogates = 0;
1649 *maxchar = 0;
1650
1651 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001653 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1654 && (iter+1) < end
1655 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1656 {
1657 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1658 ++(*num_surrogates);
1659 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001660 }
1661 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001662#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001663 {
1664 ch = *iter;
1665 iter++;
1666 }
1667 if (ch > *maxchar) {
1668 *maxchar = ch;
1669 if (*maxchar > MAX_UNICODE) {
1670 PyErr_Format(PyExc_ValueError,
1671 "character U+%x is not in range [U+0000; U+10ffff]",
1672 ch);
1673 return -1;
1674 }
1675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001676 }
1677 return 0;
1678}
1679
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001680int
1681_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001682{
1683 wchar_t *end;
1684 Py_UCS4 maxchar = 0;
1685 Py_ssize_t num_surrogates;
1686#if SIZEOF_WCHAR_T == 2
1687 Py_ssize_t length_wo_surrogates;
1688#endif
1689
Georg Brandl7597add2011-10-05 16:36:47 +02001690 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001691 strings were created using _PyObject_New() and where no canonical
1692 representation (the str field) has been set yet aka strings
1693 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001694 assert(_PyUnicode_CHECK(unicode));
1695 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001696 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001697 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001698 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001699 /* Actually, it should neither be interned nor be anything else: */
1700 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001702 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001703 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001704 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001705 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706
1707 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001708 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1709 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001710 PyErr_NoMemory();
1711 return -1;
1712 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001713 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001714 _PyUnicode_WSTR(unicode), end,
1715 PyUnicode_1BYTE_DATA(unicode));
1716 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1717 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1718 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1719 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001720 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001721 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001722 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001723 }
1724 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001725 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001726 _PyUnicode_UTF8(unicode) = NULL;
1727 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001728 }
1729 PyObject_FREE(_PyUnicode_WSTR(unicode));
1730 _PyUnicode_WSTR(unicode) = NULL;
1731 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1732 }
1733 /* In this case we might have to convert down from 4-byte native
1734 wchar_t to 2-byte unicode. */
1735 else if (maxchar < 65536) {
1736 assert(num_surrogates == 0 &&
1737 "FindMaxCharAndNumSurrogatePairs() messed up");
1738
Victor Stinner506f5922011-09-28 22:34:18 +02001739#if SIZEOF_WCHAR_T == 2
1740 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001741 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001742 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1743 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1744 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001745 _PyUnicode_UTF8(unicode) = NULL;
1746 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001747#else
1748 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001749 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001750 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001751 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001752 PyErr_NoMemory();
1753 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754 }
Victor Stinner506f5922011-09-28 22:34:18 +02001755 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1756 _PyUnicode_WSTR(unicode), end,
1757 PyUnicode_2BYTE_DATA(unicode));
1758 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1759 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1760 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001761 _PyUnicode_UTF8(unicode) = NULL;
1762 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001763 PyObject_FREE(_PyUnicode_WSTR(unicode));
1764 _PyUnicode_WSTR(unicode) = NULL;
1765 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1766#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001767 }
1768 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1769 else {
1770#if SIZEOF_WCHAR_T == 2
1771 /* in case the native representation is 2-bytes, we need to allocate a
1772 new normalized 4-byte version. */
1773 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001774 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1775 PyErr_NoMemory();
1776 return -1;
1777 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001778 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1779 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001780 PyErr_NoMemory();
1781 return -1;
1782 }
1783 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1784 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001785 _PyUnicode_UTF8(unicode) = NULL;
1786 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001787 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1788 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001789 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001790 PyObject_FREE(_PyUnicode_WSTR(unicode));
1791 _PyUnicode_WSTR(unicode) = NULL;
1792 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1793#else
1794 assert(num_surrogates == 0);
1795
Victor Stinnerc3c74152011-10-02 20:39:55 +02001796 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001797 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001798 _PyUnicode_UTF8(unicode) = NULL;
1799 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1801#endif
1802 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1803 }
1804 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001805 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001806 return 0;
1807}
1808
Alexander Belopolsky40018472011-02-26 01:02:56 +00001809static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001810unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001811{
Walter Dörwald16807132007-05-25 13:52:07 +00001812 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001813 case SSTATE_NOT_INTERNED:
1814 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001815
Benjamin Peterson29060642009-01-31 22:14:21 +00001816 case SSTATE_INTERNED_MORTAL:
1817 /* revive dead object temporarily for DelItem */
1818 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001819 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001820 Py_FatalError(
1821 "deletion of interned string failed");
1822 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001823
Benjamin Peterson29060642009-01-31 22:14:21 +00001824 case SSTATE_INTERNED_IMMORTAL:
1825 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001826 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001827
Benjamin Peterson29060642009-01-31 22:14:21 +00001828 default:
1829 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001830 }
1831
Victor Stinner03490912011-10-03 23:45:12 +02001832 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001834 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001835 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001836 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1837 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001838
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001839 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001840}
1841
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001842#ifdef Py_DEBUG
1843static int
1844unicode_is_singleton(PyObject *unicode)
1845{
1846 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1847 if (unicode == unicode_empty)
1848 return 1;
1849 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1850 {
1851 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1852 if (ch < 256 && unicode_latin1[ch] == unicode)
1853 return 1;
1854 }
1855 return 0;
1856}
1857#endif
1858
Alexander Belopolsky40018472011-02-26 01:02:56 +00001859static int
Victor Stinner488fa492011-12-12 00:01:39 +01001860unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001861{
Victor Stinner488fa492011-12-12 00:01:39 +01001862 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001863 if (Py_REFCNT(unicode) != 1)
1864 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001865 if (_PyUnicode_HASH(unicode) != -1)
1866 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001867 if (PyUnicode_CHECK_INTERNED(unicode))
1868 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001869 if (!PyUnicode_CheckExact(unicode))
1870 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001871#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001872 /* singleton refcount is greater than 1 */
1873 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001874#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001875 return 1;
1876}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001877
Victor Stinnerfe226c02011-10-03 03:52:20 +02001878static int
1879unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1880{
1881 PyObject *unicode;
1882 Py_ssize_t old_length;
1883
1884 assert(p_unicode != NULL);
1885 unicode = *p_unicode;
1886
1887 assert(unicode != NULL);
1888 assert(PyUnicode_Check(unicode));
1889 assert(0 <= length);
1890
Victor Stinner910337b2011-10-03 03:20:16 +02001891 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001892 old_length = PyUnicode_WSTR_LENGTH(unicode);
1893 else
1894 old_length = PyUnicode_GET_LENGTH(unicode);
1895 if (old_length == length)
1896 return 0;
1897
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001898 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001899 _Py_INCREF_UNICODE_EMPTY();
1900 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001901 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001902 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001903 return 0;
1904 }
1905
Victor Stinner488fa492011-12-12 00:01:39 +01001906 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001907 PyObject *copy = resize_copy(unicode, length);
1908 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001909 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001910 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001911 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001912 }
1913
Victor Stinnerfe226c02011-10-03 03:52:20 +02001914 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001915 PyObject *new_unicode = resize_compact(unicode, length);
1916 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001917 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001918 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001919 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001920 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001921 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001922}
1923
Alexander Belopolsky40018472011-02-26 01:02:56 +00001924int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001925PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001926{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001927 PyObject *unicode;
1928 if (p_unicode == NULL) {
1929 PyErr_BadInternalCall();
1930 return -1;
1931 }
1932 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001933 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001934 {
1935 PyErr_BadInternalCall();
1936 return -1;
1937 }
1938 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001939}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001940
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001941/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001942
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001943 WARNING: The function doesn't copy the terminating null character and
1944 doesn't check the maximum character (may write a latin1 character in an
1945 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001946static void
1947unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1948 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001949{
1950 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1951 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001952 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001953
1954 switch (kind) {
1955 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001956 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001957#ifdef Py_DEBUG
1958 if (PyUnicode_IS_ASCII(unicode)) {
1959 Py_UCS4 maxchar = ucs1lib_find_max_char(
1960 (const Py_UCS1*)str,
1961 (const Py_UCS1*)str + len);
1962 assert(maxchar < 128);
1963 }
1964#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001965 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001966 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001967 }
1968 case PyUnicode_2BYTE_KIND: {
1969 Py_UCS2 *start = (Py_UCS2 *)data + index;
1970 Py_UCS2 *ucs2 = start;
1971 assert(index <= PyUnicode_GET_LENGTH(unicode));
1972
Victor Stinner184252a2012-06-16 02:57:41 +02001973 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001974 *ucs2 = (Py_UCS2)*str;
1975
1976 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001977 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001978 }
1979 default: {
1980 Py_UCS4 *start = (Py_UCS4 *)data + index;
1981 Py_UCS4 *ucs4 = start;
1982 assert(kind == PyUnicode_4BYTE_KIND);
1983 assert(index <= PyUnicode_GET_LENGTH(unicode));
1984
Victor Stinner184252a2012-06-16 02:57:41 +02001985 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001986 *ucs4 = (Py_UCS4)*str;
1987
1988 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001989 }
1990 }
1991}
1992
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001993static PyObject*
1994get_latin1_char(unsigned char ch)
1995{
Victor Stinnera464fc12011-10-02 20:39:30 +02001996 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001997 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001998 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 if (!unicode)
2000 return NULL;
2001 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002002 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 unicode_latin1[ch] = unicode;
2004 }
2005 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02002006 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002007}
2008
Victor Stinner985a82a2014-01-03 12:53:47 +01002009static PyObject*
2010unicode_char(Py_UCS4 ch)
2011{
2012 PyObject *unicode;
2013
2014 assert(ch <= MAX_UNICODE);
2015
Victor Stinnerf3b46b42014-01-03 13:16:00 +01002016 if (ch < 256)
2017 return get_latin1_char(ch);
2018
Victor Stinner985a82a2014-01-03 12:53:47 +01002019 unicode = PyUnicode_New(1, ch);
2020 if (unicode == NULL)
2021 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002022
2023 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
2024 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01002025 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002026 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01002027 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
2028 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
2029 }
2030 assert(_PyUnicode_CheckConsistency(unicode, 1));
2031 return unicode;
2032}
2033
Alexander Belopolsky40018472011-02-26 01:02:56 +00002034PyObject *
2035PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002036{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002037 if (u == NULL)
2038 return (PyObject*)_PyUnicode_New(size);
2039
2040 if (size < 0) {
2041 PyErr_BadInternalCall();
2042 return NULL;
2043 }
2044
2045 return PyUnicode_FromWideChar(u, size);
2046}
2047
2048PyObject *
2049PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2050{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002051 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002052 Py_UCS4 maxchar = 0;
2053 Py_ssize_t num_surrogates;
2054
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002055 if (u == NULL && size != 0) {
2056 PyErr_BadInternalCall();
2057 return NULL;
2058 }
2059
2060 if (size == -1) {
2061 size = wcslen(u);
2062 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002063
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002064 /* If the Unicode data is known at construction time, we can apply
2065 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002067 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002068 if (size == 0)
2069 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002071 /* Single character Unicode objects in the Latin-1 range are
2072 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002073 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074 return get_latin1_char((unsigned char)*u);
2075
2076 /* If not empty and not single character, copy the Unicode data
2077 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002078 if (find_maxchar_surrogates(u, u + size,
2079 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002080 return NULL;
2081
Victor Stinner8faf8212011-12-08 22:14:11 +01002082 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002083 if (!unicode)
2084 return NULL;
2085
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002086 switch (PyUnicode_KIND(unicode)) {
2087 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002088 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002089 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2090 break;
2091 case PyUnicode_2BYTE_KIND:
2092#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002093 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002094#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002095 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002096 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2097#endif
2098 break;
2099 case PyUnicode_4BYTE_KIND:
2100#if SIZEOF_WCHAR_T == 2
2101 /* This is the only case which has to process surrogates, thus
2102 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002103 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002104#else
2105 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002106 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002107#endif
2108 break;
2109 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002110 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002111 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002112
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002113 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002114}
2115
Alexander Belopolsky40018472011-02-26 01:02:56 +00002116PyObject *
2117PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002118{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002119 if (size < 0) {
2120 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002121 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002122 return NULL;
2123 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002124 if (u != NULL)
2125 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2126 else
2127 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002128}
2129
Alexander Belopolsky40018472011-02-26 01:02:56 +00002130PyObject *
2131PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002132{
2133 size_t size = strlen(u);
2134 if (size > PY_SSIZE_T_MAX) {
2135 PyErr_SetString(PyExc_OverflowError, "input too long");
2136 return NULL;
2137 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002138 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002139}
2140
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002141PyObject *
2142_PyUnicode_FromId(_Py_Identifier *id)
2143{
2144 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002145 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2146 strlen(id->string),
2147 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002148 if (!id->object)
2149 return NULL;
2150 PyUnicode_InternInPlace(&id->object);
2151 assert(!id->next);
2152 id->next = static_strings;
2153 static_strings = id;
2154 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002155 return id->object;
2156}
2157
2158void
2159_PyUnicode_ClearStaticStrings()
2160{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002161 _Py_Identifier *tmp, *s = static_strings;
2162 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002163 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002164 tmp = s->next;
2165 s->next = NULL;
2166 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002167 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002168 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002169}
2170
Benjamin Peterson0df54292012-03-26 14:50:32 -04002171/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002172
Victor Stinnerd3f08822012-05-29 12:57:52 +02002173PyObject*
2174_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002175{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002176 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002177 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002178 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002179#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002180 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002181#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002182 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002183 }
Victor Stinner785938e2011-12-11 20:09:03 +01002184 unicode = PyUnicode_New(size, 127);
2185 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002186 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002187 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2188 assert(_PyUnicode_CheckConsistency(unicode, 1));
2189 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002190}
2191
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002192static Py_UCS4
2193kind_maxchar_limit(unsigned int kind)
2194{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002195 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002196 case PyUnicode_1BYTE_KIND:
2197 return 0x80;
2198 case PyUnicode_2BYTE_KIND:
2199 return 0x100;
2200 case PyUnicode_4BYTE_KIND:
2201 return 0x10000;
2202 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002203 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002204 }
2205}
2206
Victor Stinner702c7342011-10-05 13:50:52 +02002207static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002208_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002209{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002210 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002211 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002212
Serhiy Storchaka678db842013-01-26 12:16:36 +02002213 if (size == 0)
2214 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002215 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002216 if (size == 1)
2217 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002218
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002219 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002220 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002221 if (!res)
2222 return NULL;
2223 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002224 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002225 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002226}
2227
Victor Stinnere57b1c02011-09-28 22:20:48 +02002228static PyObject*
2229_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002230{
2231 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002232 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002233
Serhiy Storchaka678db842013-01-26 12:16:36 +02002234 if (size == 0)
2235 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002236 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002237 if (size == 1)
2238 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002239
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002240 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002241 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 if (!res)
2243 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002244 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002245 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002246 else {
2247 _PyUnicode_CONVERT_BYTES(
2248 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2249 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002250 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002251 return res;
2252}
2253
Victor Stinnere57b1c02011-09-28 22:20:48 +02002254static PyObject*
2255_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002256{
2257 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002258 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002259
Serhiy Storchaka678db842013-01-26 12:16:36 +02002260 if (size == 0)
2261 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002262 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002263 if (size == 1)
2264 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002265
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002266 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002267 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002268 if (!res)
2269 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002270 if (max_char < 256)
2271 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2272 PyUnicode_1BYTE_DATA(res));
2273 else if (max_char < 0x10000)
2274 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2275 PyUnicode_2BYTE_DATA(res));
2276 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002277 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002278 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002279 return res;
2280}
2281
2282PyObject*
2283PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2284{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002285 if (size < 0) {
2286 PyErr_SetString(PyExc_ValueError, "size must be positive");
2287 return NULL;
2288 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002289 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002290 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002291 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002292 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002293 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002294 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002295 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002296 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002297 PyErr_SetString(PyExc_SystemError, "invalid kind");
2298 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002300}
2301
Victor Stinnerece58de2012-04-23 23:36:38 +02002302Py_UCS4
2303_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2304{
2305 enum PyUnicode_Kind kind;
2306 void *startptr, *endptr;
2307
2308 assert(PyUnicode_IS_READY(unicode));
2309 assert(0 <= start);
2310 assert(end <= PyUnicode_GET_LENGTH(unicode));
2311 assert(start <= end);
2312
2313 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2314 return PyUnicode_MAX_CHAR_VALUE(unicode);
2315
2316 if (start == end)
2317 return 127;
2318
Victor Stinner94d558b2012-04-27 22:26:58 +02002319 if (PyUnicode_IS_ASCII(unicode))
2320 return 127;
2321
Victor Stinnerece58de2012-04-23 23:36:38 +02002322 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002323 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002324 endptr = (char *)startptr + end * kind;
2325 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002326 switch(kind) {
2327 case PyUnicode_1BYTE_KIND:
2328 return ucs1lib_find_max_char(startptr, endptr);
2329 case PyUnicode_2BYTE_KIND:
2330 return ucs2lib_find_max_char(startptr, endptr);
2331 case PyUnicode_4BYTE_KIND:
2332 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002333 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002334 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002335 }
2336}
2337
Victor Stinner25a4b292011-10-06 12:31:55 +02002338/* Ensure that a string uses the most efficient storage, if it is not the
2339 case: create a new string with of the right kind. Write NULL into *p_unicode
2340 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002341static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002342unicode_adjust_maxchar(PyObject **p_unicode)
2343{
2344 PyObject *unicode, *copy;
2345 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002346 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002347 unsigned int kind;
2348
2349 assert(p_unicode != NULL);
2350 unicode = *p_unicode;
2351 assert(PyUnicode_IS_READY(unicode));
2352 if (PyUnicode_IS_ASCII(unicode))
2353 return;
2354
2355 len = PyUnicode_GET_LENGTH(unicode);
2356 kind = PyUnicode_KIND(unicode);
2357 if (kind == PyUnicode_1BYTE_KIND) {
2358 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002359 max_char = ucs1lib_find_max_char(u, u + len);
2360 if (max_char >= 128)
2361 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002362 }
2363 else if (kind == PyUnicode_2BYTE_KIND) {
2364 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002365 max_char = ucs2lib_find_max_char(u, u + len);
2366 if (max_char >= 256)
2367 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002368 }
2369 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002370 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002371 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002372 max_char = ucs4lib_find_max_char(u, u + len);
2373 if (max_char >= 0x10000)
2374 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002375 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002376 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002377 if (copy != NULL)
2378 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002379 Py_DECREF(unicode);
2380 *p_unicode = copy;
2381}
2382
Victor Stinner034f6cf2011-09-30 02:26:44 +02002383PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002384_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002385{
Victor Stinner87af4f22011-11-21 23:03:47 +01002386 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002387 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002388
Victor Stinner034f6cf2011-09-30 02:26:44 +02002389 if (!PyUnicode_Check(unicode)) {
2390 PyErr_BadInternalCall();
2391 return NULL;
2392 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002393 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002394 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002395
Victor Stinner87af4f22011-11-21 23:03:47 +01002396 length = PyUnicode_GET_LENGTH(unicode);
2397 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002398 if (!copy)
2399 return NULL;
2400 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2401
Christian Heimesf051e432016-09-13 20:22:02 +02002402 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002403 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002404 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002405 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002406}
2407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002408
Victor Stinnerbc603d12011-10-02 01:00:40 +02002409/* Widen Unicode objects to larger buffers. Don't write terminating null
2410 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411
2412void*
2413_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2414{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002415 Py_ssize_t len;
2416 void *result;
2417 unsigned int skind;
2418
Benjamin Petersonbac79492012-01-14 13:34:47 -05002419 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002420 return NULL;
2421
2422 len = PyUnicode_GET_LENGTH(s);
2423 skind = PyUnicode_KIND(s);
2424 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002425 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 return NULL;
2427 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002428 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002429 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002430 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002431 if (!result)
2432 return PyErr_NoMemory();
2433 assert(skind == PyUnicode_1BYTE_KIND);
2434 _PyUnicode_CONVERT_BYTES(
2435 Py_UCS1, Py_UCS2,
2436 PyUnicode_1BYTE_DATA(s),
2437 PyUnicode_1BYTE_DATA(s) + len,
2438 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002440 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002441 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002442 if (!result)
2443 return PyErr_NoMemory();
2444 if (skind == PyUnicode_2BYTE_KIND) {
2445 _PyUnicode_CONVERT_BYTES(
2446 Py_UCS2, Py_UCS4,
2447 PyUnicode_2BYTE_DATA(s),
2448 PyUnicode_2BYTE_DATA(s) + len,
2449 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002450 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002451 else {
2452 assert(skind == PyUnicode_1BYTE_KIND);
2453 _PyUnicode_CONVERT_BYTES(
2454 Py_UCS1, Py_UCS4,
2455 PyUnicode_1BYTE_DATA(s),
2456 PyUnicode_1BYTE_DATA(s) + len,
2457 result);
2458 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002460 default:
2461 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002462 }
Victor Stinner01698042011-10-04 00:04:26 +02002463 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002464 return NULL;
2465}
2466
2467static Py_UCS4*
2468as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2469 int copy_null)
2470{
2471 int kind;
2472 void *data;
2473 Py_ssize_t len, targetlen;
2474 if (PyUnicode_READY(string) == -1)
2475 return NULL;
2476 kind = PyUnicode_KIND(string);
2477 data = PyUnicode_DATA(string);
2478 len = PyUnicode_GET_LENGTH(string);
2479 targetlen = len;
2480 if (copy_null)
2481 targetlen++;
2482 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002483 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002484 if (!target) {
2485 PyErr_NoMemory();
2486 return NULL;
2487 }
2488 }
2489 else {
2490 if (targetsize < targetlen) {
2491 PyErr_Format(PyExc_SystemError,
2492 "string is longer than the buffer");
2493 if (copy_null && 0 < targetsize)
2494 target[0] = 0;
2495 return NULL;
2496 }
2497 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002498 if (kind == PyUnicode_1BYTE_KIND) {
2499 Py_UCS1 *start = (Py_UCS1 *) data;
2500 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002501 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002502 else if (kind == PyUnicode_2BYTE_KIND) {
2503 Py_UCS2 *start = (Py_UCS2 *) data;
2504 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2505 }
2506 else {
2507 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002508 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002509 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002510 if (copy_null)
2511 target[len] = 0;
2512 return target;
2513}
2514
2515Py_UCS4*
2516PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2517 int copy_null)
2518{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002519 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 PyErr_BadInternalCall();
2521 return NULL;
2522 }
2523 return as_ucs4(string, target, targetsize, copy_null);
2524}
2525
2526Py_UCS4*
2527PyUnicode_AsUCS4Copy(PyObject *string)
2528{
2529 return as_ucs4(string, NULL, 0, 1);
2530}
2531
Victor Stinner15a11362012-10-06 23:48:20 +02002532/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002533 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2534 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2535#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002536
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002537static int
2538unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2539 Py_ssize_t width, Py_ssize_t precision)
2540{
2541 Py_ssize_t length, fill, arglen;
2542 Py_UCS4 maxchar;
2543
2544 if (PyUnicode_READY(str) == -1)
2545 return -1;
2546
2547 length = PyUnicode_GET_LENGTH(str);
2548 if ((precision == -1 || precision >= length)
2549 && width <= length)
2550 return _PyUnicodeWriter_WriteStr(writer, str);
2551
2552 if (precision != -1)
2553 length = Py_MIN(precision, length);
2554
2555 arglen = Py_MAX(length, width);
2556 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2557 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2558 else
2559 maxchar = writer->maxchar;
2560
2561 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2562 return -1;
2563
2564 if (width > length) {
2565 fill = width - length;
2566 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2567 return -1;
2568 writer->pos += fill;
2569 }
2570
2571 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2572 str, 0, length);
2573 writer->pos += length;
2574 return 0;
2575}
2576
2577static int
Victor Stinner998b8062018-09-12 00:23:25 +02002578unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002579 Py_ssize_t width, Py_ssize_t precision)
2580{
2581 /* UTF-8 */
2582 Py_ssize_t length;
2583 PyObject *unicode;
2584 int res;
2585
Serhiy Storchakad586ccb2019-01-12 10:30:35 +02002586 if (precision == -1) {
2587 length = strlen(str);
2588 }
2589 else {
2590 length = 0;
2591 while (length < precision && str[length]) {
2592 length++;
2593 }
2594 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002595 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2596 if (unicode == NULL)
2597 return -1;
2598
2599 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2600 Py_DECREF(unicode);
2601 return res;
2602}
2603
Victor Stinner96865452011-03-01 23:44:09 +00002604static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002605unicode_fromformat_arg(_PyUnicodeWriter *writer,
2606 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002607{
Victor Stinnere215d962012-10-06 23:03:36 +02002608 const char *p;
2609 Py_ssize_t len;
2610 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002611 Py_ssize_t width;
2612 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002613 int longflag;
2614 int longlongflag;
2615 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002616 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002617
2618 p = f;
2619 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002620 zeropad = 0;
2621 if (*f == '0') {
2622 zeropad = 1;
2623 f++;
2624 }
Victor Stinner96865452011-03-01 23:44:09 +00002625
2626 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002627 width = -1;
2628 if (Py_ISDIGIT((unsigned)*f)) {
2629 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002630 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002631 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002632 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002633 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002634 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002635 return NULL;
2636 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002637 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002638 f++;
2639 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002640 }
2641 precision = -1;
2642 if (*f == '.') {
2643 f++;
2644 if (Py_ISDIGIT((unsigned)*f)) {
2645 precision = (*f - '0');
2646 f++;
2647 while (Py_ISDIGIT((unsigned)*f)) {
2648 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2649 PyErr_SetString(PyExc_ValueError,
2650 "precision too big");
2651 return NULL;
2652 }
2653 precision = (precision * 10) + (*f - '0');
2654 f++;
2655 }
2656 }
Victor Stinner96865452011-03-01 23:44:09 +00002657 if (*f == '%') {
2658 /* "%.3%s" => f points to "3" */
2659 f--;
2660 }
2661 }
2662 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002663 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002664 f--;
2665 }
Victor Stinner96865452011-03-01 23:44:09 +00002666
2667 /* Handle %ld, %lu, %lld and %llu. */
2668 longflag = 0;
2669 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002670 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002671 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002672 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002673 longflag = 1;
2674 ++f;
2675 }
Victor Stinner96865452011-03-01 23:44:09 +00002676 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002677 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002678 longlongflag = 1;
2679 f += 2;
2680 }
Victor Stinner96865452011-03-01 23:44:09 +00002681 }
2682 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002683 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002684 size_tflag = 1;
2685 ++f;
2686 }
Victor Stinnere215d962012-10-06 23:03:36 +02002687
2688 if (f[1] == '\0')
2689 writer->overallocate = 0;
2690
2691 switch (*f) {
2692 case 'c':
2693 {
2694 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002695 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002696 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002697 "character argument not in range(0x110000)");
2698 return NULL;
2699 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002700 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002701 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002702 break;
2703 }
2704
2705 case 'i':
2706 case 'd':
2707 case 'u':
2708 case 'x':
2709 {
2710 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002711 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002712 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002713
2714 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002715 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002716 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002717 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002718 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002719 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002720 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002721 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002722 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002723 va_arg(*vargs, size_t));
2724 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002725 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002726 va_arg(*vargs, unsigned int));
2727 }
2728 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002729 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002730 }
2731 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002732 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002733 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002734 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002735 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002736 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002737 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002738 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002739 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002740 va_arg(*vargs, Py_ssize_t));
2741 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002742 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002743 va_arg(*vargs, int));
2744 }
2745 assert(len >= 0);
2746
Victor Stinnere215d962012-10-06 23:03:36 +02002747 if (precision < len)
2748 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002749
2750 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002751 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2752 return NULL;
2753
Victor Stinnere215d962012-10-06 23:03:36 +02002754 if (width > precision) {
2755 Py_UCS4 fillchar;
2756 fill = width - precision;
2757 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002758 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2759 return NULL;
2760 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002761 }
Victor Stinner15a11362012-10-06 23:48:20 +02002762 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002763 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002764 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2765 return NULL;
2766 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002767 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002768
Victor Stinner4a587072013-11-19 12:54:53 +01002769 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2770 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002771 break;
2772 }
2773
2774 case 'p':
2775 {
2776 char number[MAX_LONG_LONG_CHARS];
2777
2778 len = sprintf(number, "%p", va_arg(*vargs, void*));
2779 assert(len >= 0);
2780
2781 /* %p is ill-defined: ensure leading 0x. */
2782 if (number[1] == 'X')
2783 number[1] = 'x';
2784 else if (number[1] != 'x') {
2785 memmove(number + 2, number,
2786 strlen(number) + 1);
2787 number[0] = '0';
2788 number[1] = 'x';
2789 len += 2;
2790 }
2791
Victor Stinner4a587072013-11-19 12:54:53 +01002792 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002793 return NULL;
2794 break;
2795 }
2796
2797 case 's':
2798 {
2799 /* UTF-8 */
2800 const char *s = va_arg(*vargs, const char*);
Victor Stinner998b8062018-09-12 00:23:25 +02002801 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002802 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002803 break;
2804 }
2805
2806 case 'U':
2807 {
2808 PyObject *obj = va_arg(*vargs, PyObject *);
2809 assert(obj && _PyUnicode_CHECK(obj));
2810
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002811 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002812 return NULL;
2813 break;
2814 }
2815
2816 case 'V':
2817 {
2818 PyObject *obj = va_arg(*vargs, PyObject *);
2819 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002820 if (obj) {
2821 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002822 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002823 return NULL;
2824 }
2825 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002826 assert(str != NULL);
Victor Stinner998b8062018-09-12 00:23:25 +02002827 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002828 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002829 }
2830 break;
2831 }
2832
2833 case 'S':
2834 {
2835 PyObject *obj = va_arg(*vargs, PyObject *);
2836 PyObject *str;
2837 assert(obj);
2838 str = PyObject_Str(obj);
2839 if (!str)
2840 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002841 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002842 Py_DECREF(str);
2843 return NULL;
2844 }
2845 Py_DECREF(str);
2846 break;
2847 }
2848
2849 case 'R':
2850 {
2851 PyObject *obj = va_arg(*vargs, PyObject *);
2852 PyObject *repr;
2853 assert(obj);
2854 repr = PyObject_Repr(obj);
2855 if (!repr)
2856 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002857 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002858 Py_DECREF(repr);
2859 return NULL;
2860 }
2861 Py_DECREF(repr);
2862 break;
2863 }
2864
2865 case 'A':
2866 {
2867 PyObject *obj = va_arg(*vargs, PyObject *);
2868 PyObject *ascii;
2869 assert(obj);
2870 ascii = PyObject_ASCII(obj);
2871 if (!ascii)
2872 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002873 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002874 Py_DECREF(ascii);
2875 return NULL;
2876 }
2877 Py_DECREF(ascii);
2878 break;
2879 }
2880
2881 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002882 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002883 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002884 break;
2885
2886 default:
2887 /* if we stumble upon an unknown formatting code, copy the rest
2888 of the format string to the output string. (we cannot just
2889 skip the code, since there's no way to know what's in the
2890 argument list) */
2891 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002892 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002893 return NULL;
2894 f = p+len;
2895 return f;
2896 }
2897
2898 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002899 return f;
2900}
2901
Walter Dörwaldd2034312007-05-18 16:29:38 +00002902PyObject *
2903PyUnicode_FromFormatV(const char *format, va_list vargs)
2904{
Victor Stinnere215d962012-10-06 23:03:36 +02002905 va_list vargs2;
2906 const char *f;
2907 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002908
Victor Stinner8f674cc2013-04-17 23:02:17 +02002909 _PyUnicodeWriter_Init(&writer);
2910 writer.min_length = strlen(format) + 100;
2911 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002912
Benjamin Peterson0c212142016-09-20 20:39:33 -07002913 // Copy varags to be able to pass a reference to a subfunction.
2914 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002915
2916 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002917 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002918 f = unicode_fromformat_arg(&writer, f, &vargs2);
2919 if (f == NULL)
2920 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002922 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002923 const char *p;
2924 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002925
Victor Stinnere215d962012-10-06 23:03:36 +02002926 p = f;
2927 do
2928 {
2929 if ((unsigned char)*p > 127) {
2930 PyErr_Format(PyExc_ValueError,
2931 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2932 "string, got a non-ASCII byte: 0x%02x",
2933 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002934 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002935 }
2936 p++;
2937 }
2938 while (*p != '\0' && *p != '%');
2939 len = p - f;
2940
2941 if (*p == '\0')
2942 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002943
2944 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002945 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002946
2947 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002948 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002949 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002950 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002951 return _PyUnicodeWriter_Finish(&writer);
2952
2953 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002954 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002955 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002956 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002957}
2958
Walter Dörwaldd2034312007-05-18 16:29:38 +00002959PyObject *
2960PyUnicode_FromFormat(const char *format, ...)
2961{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002962 PyObject* ret;
2963 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002964
2965#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002966 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002967#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002968 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002969#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002970 ret = PyUnicode_FromFormatV(format, vargs);
2971 va_end(vargs);
2972 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002973}
2974
Serhiy Storchakac46db922018-10-23 22:58:24 +03002975static Py_ssize_t
2976unicode_get_widechar_size(PyObject *unicode)
2977{
2978 Py_ssize_t res;
2979
2980 assert(unicode != NULL);
2981 assert(_PyUnicode_CHECK(unicode));
2982
2983 if (_PyUnicode_WSTR(unicode) != NULL) {
2984 return PyUnicode_WSTR_LENGTH(unicode);
2985 }
2986 assert(PyUnicode_IS_READY(unicode));
2987
2988 res = _PyUnicode_LENGTH(unicode);
2989#if SIZEOF_WCHAR_T == 2
2990 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
2991 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
2992 const Py_UCS4 *end = s + res;
2993 for (; s < end; ++s) {
2994 if (*s > 0xFFFF) {
2995 ++res;
2996 }
2997 }
2998 }
2999#endif
3000 return res;
3001}
3002
3003static void
3004unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
3005{
3006 const wchar_t *wstr;
3007
3008 assert(unicode != NULL);
3009 assert(_PyUnicode_CHECK(unicode));
3010
3011 wstr = _PyUnicode_WSTR(unicode);
3012 if (wstr != NULL) {
3013 memcpy(w, wstr, size * sizeof(wchar_t));
3014 return;
3015 }
3016 assert(PyUnicode_IS_READY(unicode));
3017
3018 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3019 const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3020 for (; size--; ++s, ++w) {
3021 *w = *s;
3022 }
3023 }
3024 else {
3025#if SIZEOF_WCHAR_T == 4
3026 assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3027 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3028 for (; size--; ++s, ++w) {
3029 *w = *s;
3030 }
3031#else
3032 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
3033 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3034 for (; size--; ++s, ++w) {
3035 Py_UCS4 ch = *s;
3036 if (ch > 0xFFFF) {
3037 assert(ch <= MAX_UNICODE);
3038 /* encode surrogate pair in this case */
3039 *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
3040 if (!size--)
3041 break;
3042 *w = Py_UNICODE_LOW_SURROGATE(ch);
3043 }
3044 else {
3045 *w = ch;
3046 }
3047 }
3048#endif
3049 }
3050}
3051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003052#ifdef HAVE_WCHAR_H
3053
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003054/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00003055
Victor Stinnerd88d9832011-09-06 02:00:05 +02003056 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003057 character) required to convert the unicode object. Ignore size argument.
3058
Victor Stinnerd88d9832011-09-06 02:00:05 +02003059 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003060 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02003061 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003062Py_ssize_t
3063PyUnicode_AsWideChar(PyObject *unicode,
3064 wchar_t *w,
3065 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00003066{
Victor Stinner5593d8a2010-10-02 11:11:27 +00003067 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003068
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003069 if (unicode == NULL) {
3070 PyErr_BadInternalCall();
3071 return -1;
3072 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003073 if (!PyUnicode_Check(unicode)) {
3074 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003075 return -1;
Victor Stinner5593d8a2010-10-02 11:11:27 +00003076 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003077
3078 res = unicode_get_widechar_size(unicode);
3079 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003080 return res + 1;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003081 }
3082
3083 if (size > res) {
3084 size = res + 1;
3085 }
3086 else {
3087 res = size;
3088 }
3089 unicode_copy_as_widechar(unicode, w, size);
3090 return res;
Victor Stinner137c34c2010-09-29 10:25:54 +00003091}
3092
Victor Stinner137c34c2010-09-29 10:25:54 +00003093wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003094PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00003095 Py_ssize_t *size)
3096{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003097 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00003098 Py_ssize_t buflen;
3099
3100 if (unicode == NULL) {
3101 PyErr_BadInternalCall();
3102 return NULL;
3103 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003104 if (!PyUnicode_Check(unicode)) {
3105 PyErr_BadArgument();
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003106 return NULL;
3107 }
3108
Serhiy Storchakac46db922018-10-23 22:58:24 +03003109 buflen = unicode_get_widechar_size(unicode);
3110 buffer = (wchar_t *) PyMem_NEW(wchar_t, (buflen + 1));
Victor Stinner137c34c2010-09-29 10:25:54 +00003111 if (buffer == NULL) {
3112 PyErr_NoMemory();
3113 return NULL;
3114 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003115 unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3116 if (size != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00003117 *size = buflen;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003118 }
3119 else if (wcslen(buffer) != (size_t)buflen) {
3120 PyMem_FREE(buffer);
3121 PyErr_SetString(PyExc_ValueError,
3122 "embedded null character");
3123 return NULL;
3124 }
Victor Stinner137c34c2010-09-29 10:25:54 +00003125 return buffer;
3126}
3127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003128#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003129
Alexander Belopolsky40018472011-02-26 01:02:56 +00003130PyObject *
3131PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003132{
Victor Stinner8faf8212011-12-08 22:14:11 +01003133 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003134 PyErr_SetString(PyExc_ValueError,
3135 "chr() arg not in range(0x110000)");
3136 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003137 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003138
Victor Stinner985a82a2014-01-03 12:53:47 +01003139 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003140}
3141
Alexander Belopolsky40018472011-02-26 01:02:56 +00003142PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003143PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003144{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003145 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003146 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003147 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003148 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003149 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003150 Py_INCREF(obj);
3151 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003152 }
3153 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003154 /* For a Unicode subtype that's not a Unicode object,
3155 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003156 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003157 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003158 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003159 "Can't convert '%.100s' object to str implicitly",
3160 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003161 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003162}
3163
Alexander Belopolsky40018472011-02-26 01:02:56 +00003164PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003165PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003166 const char *encoding,
3167 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003168{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003169 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003170 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003171
Guido van Rossumd57fd912000-03-10 22:53:23 +00003172 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003173 PyErr_BadInternalCall();
3174 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003175 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003176
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003177 /* Decoding bytes objects is the most common case and should be fast */
3178 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003179 if (PyBytes_GET_SIZE(obj) == 0)
3180 _Py_RETURN_UNICODE_EMPTY();
3181 v = PyUnicode_Decode(
3182 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3183 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003184 return v;
3185 }
3186
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003187 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003188 PyErr_SetString(PyExc_TypeError,
3189 "decoding str is not supported");
3190 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003191 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003192
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003193 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3194 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3195 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003196 "decoding to str: need a bytes-like object, %.80s found",
3197 Py_TYPE(obj)->tp_name);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003198 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003199 }
Tim Petersced69f82003-09-16 20:30:58 +00003200
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003201 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003202 PyBuffer_Release(&buffer);
3203 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003204 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003205
Serhiy Storchaka05997252013-01-26 12:14:02 +02003206 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003207 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003208 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209}
3210
Victor Stinnerebe17e02016-10-12 13:57:45 +02003211/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3212 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3213 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003214int
3215_Py_normalize_encoding(const char *encoding,
3216 char *lower,
3217 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003218{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003219 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003220 char *l;
3221 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003222 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003223
Victor Stinner942889a2016-09-05 15:40:10 -07003224 assert(encoding != NULL);
3225
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003226 e = encoding;
3227 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003228 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003229 punct = 0;
3230 while (1) {
3231 char c = *e;
3232 if (c == 0) {
3233 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003234 }
Victor Stinner942889a2016-09-05 15:40:10 -07003235
3236 if (Py_ISALNUM(c) || c == '.') {
3237 if (punct && l != lower) {
3238 if (l == l_end) {
3239 return 0;
3240 }
3241 *l++ = '_';
3242 }
3243 punct = 0;
3244
3245 if (l == l_end) {
3246 return 0;
3247 }
3248 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003249 }
3250 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003251 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003252 }
Victor Stinner942889a2016-09-05 15:40:10 -07003253
3254 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003255 }
3256 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003257 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003258}
3259
Alexander Belopolsky40018472011-02-26 01:02:56 +00003260PyObject *
3261PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003262 Py_ssize_t size,
3263 const char *encoding,
3264 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003265{
3266 PyObject *buffer = NULL, *unicode;
3267 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003268 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3269
3270 if (encoding == NULL) {
3271 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3272 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003273
Fred Drakee4315f52000-05-09 19:53:39 +00003274 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003275 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3276 char *lower = buflower;
3277
3278 /* Fast paths */
3279 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3280 lower += 3;
3281 if (*lower == '_') {
3282 /* Match "utf8" and "utf_8" */
3283 lower++;
3284 }
3285
3286 if (lower[0] == '8' && lower[1] == 0) {
3287 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3288 }
3289 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3290 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3291 }
3292 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3293 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3294 }
3295 }
3296 else {
3297 if (strcmp(lower, "ascii") == 0
3298 || strcmp(lower, "us_ascii") == 0) {
3299 return PyUnicode_DecodeASCII(s, size, errors);
3300 }
Steve Dowercc16be82016-09-08 10:35:16 -07003301 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003302 else if (strcmp(lower, "mbcs") == 0) {
3303 return PyUnicode_DecodeMBCS(s, size, errors);
3304 }
3305 #endif
3306 else if (strcmp(lower, "latin1") == 0
3307 || strcmp(lower, "latin_1") == 0
3308 || strcmp(lower, "iso_8859_1") == 0
3309 || strcmp(lower, "iso8859_1") == 0) {
3310 return PyUnicode_DecodeLatin1(s, size, errors);
3311 }
3312 }
Victor Stinner37296e82010-06-10 13:36:23 +00003313 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003314
3315 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003316 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003317 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003318 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003319 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003320 if (buffer == NULL)
3321 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003322 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003323 if (unicode == NULL)
3324 goto onError;
3325 if (!PyUnicode_Check(unicode)) {
3326 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003327 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003328 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003329 encoding,
3330 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003331 Py_DECREF(unicode);
3332 goto onError;
3333 }
3334 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003335 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003336
Benjamin Peterson29060642009-01-31 22:14:21 +00003337 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003338 Py_XDECREF(buffer);
3339 return NULL;
3340}
3341
Alexander Belopolsky40018472011-02-26 01:02:56 +00003342PyObject *
3343PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003344 const char *encoding,
3345 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003346{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003347 if (!PyUnicode_Check(unicode)) {
3348 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003349 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003350 }
3351
Serhiy Storchaka00939072016-10-27 21:05:49 +03003352 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3353 "PyUnicode_AsDecodedObject() is deprecated; "
3354 "use PyCodec_Decode() to decode from str", 1) < 0)
3355 return NULL;
3356
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003357 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003358 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003359
3360 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003361 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003362}
3363
Alexander Belopolsky40018472011-02-26 01:02:56 +00003364PyObject *
3365PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003366 const char *encoding,
3367 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003368{
3369 PyObject *v;
3370
3371 if (!PyUnicode_Check(unicode)) {
3372 PyErr_BadArgument();
3373 goto onError;
3374 }
3375
Serhiy Storchaka00939072016-10-27 21:05:49 +03003376 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3377 "PyUnicode_AsDecodedUnicode() is deprecated; "
3378 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3379 return NULL;
3380
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003381 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003382 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003383
3384 /* Decode via the codec registry */
3385 v = PyCodec_Decode(unicode, encoding, errors);
3386 if (v == NULL)
3387 goto onError;
3388 if (!PyUnicode_Check(v)) {
3389 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003390 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003391 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003392 encoding,
3393 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003394 Py_DECREF(v);
3395 goto onError;
3396 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003397 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003398
Benjamin Peterson29060642009-01-31 22:14:21 +00003399 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003400 return NULL;
3401}
3402
Alexander Belopolsky40018472011-02-26 01:02:56 +00003403PyObject *
3404PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003405 Py_ssize_t size,
3406 const char *encoding,
3407 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003408{
3409 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003410
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003411 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003412 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003413 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003414 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3415 Py_DECREF(unicode);
3416 return v;
3417}
3418
Alexander Belopolsky40018472011-02-26 01:02:56 +00003419PyObject *
3420PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003421 const char *encoding,
3422 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003423{
3424 PyObject *v;
3425
3426 if (!PyUnicode_Check(unicode)) {
3427 PyErr_BadArgument();
3428 goto onError;
3429 }
3430
Serhiy Storchaka00939072016-10-27 21:05:49 +03003431 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3432 "PyUnicode_AsEncodedObject() is deprecated; "
3433 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3434 "or PyCodec_Encode() for generic encoding", 1) < 0)
3435 return NULL;
3436
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003437 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003438 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003439
3440 /* Encode via the codec registry */
3441 v = PyCodec_Encode(unicode, encoding, errors);
3442 if (v == NULL)
3443 goto onError;
3444 return v;
3445
Benjamin Peterson29060642009-01-31 22:14:21 +00003446 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003447 return NULL;
3448}
3449
Victor Stinner1b579672011-12-17 05:47:23 +01003450
Victor Stinner2cba6b82018-01-10 22:46:15 +01003451static PyObject *
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003452unicode_encode_locale(PyObject *unicode, const char *errors,
3453 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003454{
Victor Stinner3d4226a2018-08-29 22:21:32 +02003455 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003456
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003457 Py_ssize_t wlen;
3458 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3459 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003460 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003461 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003462
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003463 if ((size_t)wlen != wcslen(wstr)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003464 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003465 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003466 return NULL;
3467 }
3468
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003469 char *str;
3470 size_t error_pos;
3471 const char *reason;
3472 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003473 current_locale, error_handler);
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003474 PyMem_Free(wstr);
3475
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003476 if (res != 0) {
3477 if (res == -2) {
3478 PyObject *exc;
3479 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3480 "locale", unicode,
3481 (Py_ssize_t)error_pos,
3482 (Py_ssize_t)(error_pos+1),
3483 reason);
3484 if (exc != NULL) {
3485 PyCodec_StrictErrors(exc);
3486 Py_DECREF(exc);
3487 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003488 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003489 else if (res == -3) {
3490 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3491 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003492 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003493 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003494 }
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003495 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003496 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003497
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003498 PyObject *bytes = PyBytes_FromString(str);
3499 PyMem_RawFree(str);
3500 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003501}
3502
Victor Stinnerad158722010-10-27 00:25:46 +00003503PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003504PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3505{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003506 return unicode_encode_locale(unicode, errors, 1);
3507}
3508
3509PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003510PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003511{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003512 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003513 const _PyCoreConfig *config = &interp->core_config;
3514#if defined(__APPLE__)
3515 return _PyUnicode_AsUTF8String(unicode, config->filesystem_errors);
3516#else
Victor Stinner793b5312011-04-27 00:24:21 +02003517 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3518 cannot use it to encode and decode filenames before it is loaded. Load
3519 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003520 implementation of the locale codec until the codec registry is
3521 initialized and the Python codec is loaded. See initfsencoding(). */
3522 if (interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003523 return PyUnicode_AsEncodedString(unicode,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003524 config->filesystem_encoding,
3525 config->filesystem_errors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003526 }
3527 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003528 return unicode_encode_locale(unicode,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003529 config->filesystem_errors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003530 }
Victor Stinnerad158722010-10-27 00:25:46 +00003531#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003532}
3533
Alexander Belopolsky40018472011-02-26 01:02:56 +00003534PyObject *
3535PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003536 const char *encoding,
3537 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003538{
3539 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003540 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003541
Guido van Rossumd57fd912000-03-10 22:53:23 +00003542 if (!PyUnicode_Check(unicode)) {
3543 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003544 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003545 }
Fred Drakee4315f52000-05-09 19:53:39 +00003546
Victor Stinner942889a2016-09-05 15:40:10 -07003547 if (encoding == NULL) {
3548 return _PyUnicode_AsUTF8String(unicode, errors);
3549 }
3550
Fred Drakee4315f52000-05-09 19:53:39 +00003551 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003552 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3553 char *lower = buflower;
3554
3555 /* Fast paths */
3556 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3557 lower += 3;
3558 if (*lower == '_') {
3559 /* Match "utf8" and "utf_8" */
3560 lower++;
3561 }
3562
3563 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003564 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003565 }
3566 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3567 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3568 }
3569 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3570 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3571 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003572 }
Victor Stinner942889a2016-09-05 15:40:10 -07003573 else {
3574 if (strcmp(lower, "ascii") == 0
3575 || strcmp(lower, "us_ascii") == 0) {
3576 return _PyUnicode_AsASCIIString(unicode, errors);
3577 }
Steve Dowercc16be82016-09-08 10:35:16 -07003578#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003579 else if (strcmp(lower, "mbcs") == 0) {
3580 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3581 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003582#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003583 else if (strcmp(lower, "latin1") == 0 ||
3584 strcmp(lower, "latin_1") == 0 ||
3585 strcmp(lower, "iso_8859_1") == 0 ||
3586 strcmp(lower, "iso8859_1") == 0) {
3587 return _PyUnicode_AsLatin1String(unicode, errors);
3588 }
3589 }
Victor Stinner37296e82010-06-10 13:36:23 +00003590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003591
3592 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003593 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003594 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003595 return NULL;
3596
3597 /* The normal path */
3598 if (PyBytes_Check(v))
3599 return v;
3600
3601 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003602 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003603 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003604 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003605
3606 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003607 "encoder %s returned bytearray instead of bytes; "
3608 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003609 encoding);
3610 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003611 Py_DECREF(v);
3612 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003613 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003614
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003615 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3616 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003617 Py_DECREF(v);
3618 return b;
3619 }
3620
3621 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003622 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003623 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003624 encoding,
3625 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003626 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003627 return NULL;
3628}
3629
Alexander Belopolsky40018472011-02-26 01:02:56 +00003630PyObject *
3631PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003632 const char *encoding,
3633 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003634{
3635 PyObject *v;
3636
3637 if (!PyUnicode_Check(unicode)) {
3638 PyErr_BadArgument();
3639 goto onError;
3640 }
3641
Serhiy Storchaka00939072016-10-27 21:05:49 +03003642 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3643 "PyUnicode_AsEncodedUnicode() is deprecated; "
3644 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3645 return NULL;
3646
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003647 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003648 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003649
3650 /* Encode via the codec registry */
3651 v = PyCodec_Encode(unicode, encoding, errors);
3652 if (v == NULL)
3653 goto onError;
3654 if (!PyUnicode_Check(v)) {
3655 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003656 "'%.400s' encoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003657 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003658 encoding,
3659 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003660 Py_DECREF(v);
3661 goto onError;
3662 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003663 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003664
Benjamin Peterson29060642009-01-31 22:14:21 +00003665 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003666 return NULL;
3667}
3668
Victor Stinner2cba6b82018-01-10 22:46:15 +01003669static PyObject*
3670unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3671 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003672{
Victor Stinner3d4226a2018-08-29 22:21:32 +02003673 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003674
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003675 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3676 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003677 return NULL;
3678 }
3679
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003680 wchar_t *wstr;
3681 size_t wlen;
3682 const char *reason;
3683 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003684 current_locale, error_handler);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003685 if (res != 0) {
3686 if (res == -2) {
3687 PyObject *exc;
3688 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3689 "locale", str, len,
3690 (Py_ssize_t)wlen,
3691 (Py_ssize_t)(wlen + 1),
3692 reason);
3693 if (exc != NULL) {
3694 PyCodec_StrictErrors(exc);
3695 Py_DECREF(exc);
3696 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003697 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003698 else if (res == -3) {
3699 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3700 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003701 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003702 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003703 }
Victor Stinner2f197072011-12-17 07:08:30 +01003704 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003705 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003706
3707 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3708 PyMem_RawFree(wstr);
3709 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003710}
3711
3712PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003713PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3714 const char *errors)
3715{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003716 return unicode_decode_locale(str, len, errors, 1);
3717}
3718
3719PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003720PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003721{
3722 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003723 return unicode_decode_locale(str, size, errors, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003724}
3725
3726
3727PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003728PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003729 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003730 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3731}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003732
Christian Heimes5894ba72007-11-04 11:43:14 +00003733PyObject*
3734PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3735{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003736 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003737 const _PyCoreConfig *config = &interp->core_config;
3738#if defined(__APPLE__)
3739 return PyUnicode_DecodeUTF8Stateful(s, size, config->filesystem_errors, NULL);
3740#else
Victor Stinner793b5312011-04-27 00:24:21 +02003741 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3742 cannot use it to encode and decode filenames before it is loaded. Load
3743 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003744 implementation of the locale codec until the codec registry is
3745 initialized and the Python codec is loaded. See initfsencoding(). */
3746 if (interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003747 return PyUnicode_Decode(s, size,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003748 config->filesystem_encoding,
3749 config->filesystem_errors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003750 }
3751 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003752 return unicode_decode_locale(s, size,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003753 config->filesystem_errors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003754 }
Victor Stinnerad158722010-10-27 00:25:46 +00003755#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003756}
3757
Martin v. Löwis011e8422009-05-05 04:43:17 +00003758
3759int
3760PyUnicode_FSConverter(PyObject* arg, void* addr)
3761{
Brett Cannonec6ce872016-09-06 15:50:29 -07003762 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003763 PyObject *output = NULL;
3764 Py_ssize_t size;
3765 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003766 if (arg == NULL) {
3767 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003768 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003769 return 1;
3770 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003771 path = PyOS_FSPath(arg);
3772 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003773 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003774 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003775 if (PyBytes_Check(path)) {
3776 output = path;
3777 }
3778 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3779 output = PyUnicode_EncodeFSDefault(path);
3780 Py_DECREF(path);
3781 if (!output) {
3782 return 0;
3783 }
3784 assert(PyBytes_Check(output));
3785 }
3786
Victor Stinner0ea2a462010-04-30 00:22:08 +00003787 size = PyBytes_GET_SIZE(output);
3788 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003789 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003790 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003791 Py_DECREF(output);
3792 return 0;
3793 }
3794 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003795 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003796}
3797
3798
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003799int
3800PyUnicode_FSDecoder(PyObject* arg, void* addr)
3801{
Brett Cannona5711202016-09-06 19:36:01 -07003802 int is_buffer = 0;
3803 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003804 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003805 if (arg == NULL) {
3806 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003807 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003808 return 1;
3809 }
Brett Cannona5711202016-09-06 19:36:01 -07003810
3811 is_buffer = PyObject_CheckBuffer(arg);
3812 if (!is_buffer) {
3813 path = PyOS_FSPath(arg);
3814 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003815 return 0;
3816 }
Brett Cannona5711202016-09-06 19:36:01 -07003817 }
3818 else {
3819 path = arg;
3820 Py_INCREF(arg);
3821 }
3822
3823 if (PyUnicode_Check(path)) {
Brett Cannona5711202016-09-06 19:36:01 -07003824 output = path;
3825 }
3826 else if (PyBytes_Check(path) || is_buffer) {
3827 PyObject *path_bytes = NULL;
3828
3829 if (!PyBytes_Check(path) &&
3830 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Victor Stinner998b8062018-09-12 00:23:25 +02003831 "path should be string, bytes, or os.PathLike, not %.200s",
3832 Py_TYPE(arg)->tp_name)) {
3833 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003834 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003835 }
3836 path_bytes = PyBytes_FromObject(path);
3837 Py_DECREF(path);
3838 if (!path_bytes) {
3839 return 0;
3840 }
3841 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3842 PyBytes_GET_SIZE(path_bytes));
3843 Py_DECREF(path_bytes);
3844 if (!output) {
3845 return 0;
3846 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003847 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003848 else {
3849 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003850 "path should be string, bytes, or os.PathLike, not %.200s",
3851 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003852 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003853 return 0;
3854 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003855 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003856 Py_DECREF(output);
3857 return 0;
3858 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003860 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003861 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003862 Py_DECREF(output);
3863 return 0;
3864 }
3865 *(PyObject**)addr = output;
3866 return Py_CLEANUP_SUPPORTED;
3867}
3868
3869
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003870const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003871PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003872{
Christian Heimesf3863112007-11-22 07:46:41 +00003873 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003875 if (!PyUnicode_Check(unicode)) {
3876 PyErr_BadArgument();
3877 return NULL;
3878 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003879 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003880 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003881
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003882 if (PyUnicode_UTF8(unicode) == NULL) {
3883 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003884 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003885 if (bytes == NULL)
3886 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003887 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3888 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003889 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003890 Py_DECREF(bytes);
3891 return NULL;
3892 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003893 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003894 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003895 PyBytes_AS_STRING(bytes),
3896 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003897 Py_DECREF(bytes);
3898 }
3899
3900 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003901 *psize = PyUnicode_UTF8_LENGTH(unicode);
3902 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003903}
3904
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003905const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003906PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003907{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3909}
3910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911Py_UNICODE *
3912PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3913{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003914 if (!PyUnicode_Check(unicode)) {
3915 PyErr_BadArgument();
3916 return NULL;
3917 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003918 Py_UNICODE *w = _PyUnicode_WSTR(unicode);
3919 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003920 /* Non-ASCII compact unicode object */
Serhiy Storchakac46db922018-10-23 22:58:24 +03003921 assert(_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003922 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003923
Serhiy Storchakac46db922018-10-23 22:58:24 +03003924 Py_ssize_t wlen = unicode_get_widechar_size(unicode);
3925 if ((size_t)wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3926 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003927 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003928 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003929 w = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) * (wlen + 1));
3930 if (w == NULL) {
3931 PyErr_NoMemory();
3932 return NULL;
3933 }
3934 unicode_copy_as_widechar(unicode, w, wlen + 1);
3935 _PyUnicode_WSTR(unicode) = w;
3936 if (!PyUnicode_IS_COMPACT_ASCII(unicode)) {
3937 _PyUnicode_WSTR_LENGTH(unicode) = wlen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003938 }
3939 }
3940 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003941 *size = PyUnicode_WSTR_LENGTH(unicode);
Serhiy Storchakac46db922018-10-23 22:58:24 +03003942 return w;
Martin v. Löwis5b222132007-06-10 09:51:05 +00003943}
3944
Alexander Belopolsky40018472011-02-26 01:02:56 +00003945Py_UNICODE *
3946PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003947{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003948 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003949}
3950
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03003951const Py_UNICODE *
3952_PyUnicode_AsUnicode(PyObject *unicode)
3953{
3954 Py_ssize_t size;
3955 const Py_UNICODE *wstr;
3956
3957 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
3958 if (wstr && wcslen(wstr) != (size_t)size) {
3959 PyErr_SetString(PyExc_ValueError, "embedded null character");
3960 return NULL;
3961 }
3962 return wstr;
3963}
3964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003965
Alexander Belopolsky40018472011-02-26 01:02:56 +00003966Py_ssize_t
3967PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003968{
3969 if (!PyUnicode_Check(unicode)) {
3970 PyErr_BadArgument();
3971 goto onError;
3972 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003973 if (_PyUnicode_WSTR(unicode) == NULL) {
3974 if (PyUnicode_AsUnicode(unicode) == NULL)
3975 goto onError;
3976 }
3977 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003978
Benjamin Peterson29060642009-01-31 22:14:21 +00003979 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003980 return -1;
3981}
3982
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003983Py_ssize_t
3984PyUnicode_GetLength(PyObject *unicode)
3985{
Victor Stinner07621332012-06-16 04:53:46 +02003986 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003987 PyErr_BadArgument();
3988 return -1;
3989 }
Victor Stinner07621332012-06-16 04:53:46 +02003990 if (PyUnicode_READY(unicode) == -1)
3991 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003992 return PyUnicode_GET_LENGTH(unicode);
3993}
3994
3995Py_UCS4
3996PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3997{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003998 void *data;
3999 int kind;
4000
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004001 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004002 PyErr_BadArgument();
4003 return (Py_UCS4)-1;
4004 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03004005 if (PyUnicode_READY(unicode) == -1) {
4006 return (Py_UCS4)-1;
4007 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01004008 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02004009 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004010 return (Py_UCS4)-1;
4011 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004012 data = PyUnicode_DATA(unicode);
4013 kind = PyUnicode_KIND(unicode);
4014 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004015}
4016
4017int
4018PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4019{
4020 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004021 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004022 return -1;
4023 }
Victor Stinner488fa492011-12-12 00:01:39 +01004024 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004025 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004026 PyErr_SetString(PyExc_IndexError, "string index out of range");
4027 return -1;
4028 }
Victor Stinner488fa492011-12-12 00:01:39 +01004029 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004030 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004031 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4032 PyErr_SetString(PyExc_ValueError, "character out of range");
4033 return -1;
4034 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004035 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4036 index, ch);
4037 return 0;
4038}
4039
Alexander Belopolsky40018472011-02-26 01:02:56 +00004040const char *
4041PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004042{
Victor Stinner42cb4622010-09-01 19:39:01 +00004043 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004044}
4045
Victor Stinner554f3f02010-06-16 23:33:54 +00004046/* create or adjust a UnicodeDecodeError */
4047static void
4048make_decode_exception(PyObject **exceptionObject,
4049 const char *encoding,
4050 const char *input, Py_ssize_t length,
4051 Py_ssize_t startpos, Py_ssize_t endpos,
4052 const char *reason)
4053{
4054 if (*exceptionObject == NULL) {
4055 *exceptionObject = PyUnicodeDecodeError_Create(
4056 encoding, input, length, startpos, endpos, reason);
4057 }
4058 else {
4059 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4060 goto onError;
4061 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4062 goto onError;
4063 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4064 goto onError;
4065 }
4066 return;
4067
4068onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004069 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004070}
4071
Steve Dowercc16be82016-09-08 10:35:16 -07004072#ifdef MS_WINDOWS
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004073static int
4074widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
4075{
4076 if (newsize > *size) {
4077 wchar_t *newbuf = *buf;
4078 if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
4079 PyErr_NoMemory();
4080 return -1;
4081 }
4082 *buf = newbuf;
4083 }
4084 *size = newsize;
4085 return 0;
4086}
4087
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004088/* error handling callback helper:
4089 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004090 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004091 and adjust various state variables.
4092 return 0 on success, -1 on error
4093*/
4094
Alexander Belopolsky40018472011-02-26 01:02:56 +00004095static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004096unicode_decode_call_errorhandler_wchar(
4097 const char *errors, PyObject **errorHandler,
4098 const char *encoding, const char *reason,
4099 const char **input, const char **inend, Py_ssize_t *startinpos,
4100 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004101 wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004102{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004103 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004104
4105 PyObject *restuple = NULL;
4106 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004107 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004108 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004109 Py_ssize_t requiredsize;
4110 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004111 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004112 wchar_t *repwstr;
4113 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004114
4115 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004116 *errorHandler = PyCodec_LookupError(errors);
4117 if (*errorHandler == NULL)
4118 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004119 }
4120
Victor Stinner554f3f02010-06-16 23:33:54 +00004121 make_decode_exception(exceptionObject,
4122 encoding,
4123 *input, *inend - *input,
4124 *startinpos, *endinpos,
4125 reason);
4126 if (*exceptionObject == NULL)
4127 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004128
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004129 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004130 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004131 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004132 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004133 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004134 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004135 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004136 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004137 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004138
4139 /* Copy back the bytes variables, which might have been modified by the
4140 callback */
4141 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4142 if (!inputobj)
4143 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004144 *input = PyBytes_AS_STRING(inputobj);
4145 insize = PyBytes_GET_SIZE(inputobj);
4146 *inend = *input + insize;
4147 /* we can DECREF safely, as the exception has another reference,
4148 so the object won't go away. */
4149 Py_DECREF(inputobj);
4150
4151 if (newpos<0)
4152 newpos = insize+newpos;
4153 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004154 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004155 goto onError;
4156 }
4157
4158 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4159 if (repwstr == NULL)
4160 goto onError;
4161 /* need more space? (at least enough for what we
4162 have+the replacement+the rest of the string (starting
4163 at the new input position), so we won't have to check space
4164 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004165 requiredsize = *outpos;
4166 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4167 goto overflow;
4168 requiredsize += repwlen;
4169 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4170 goto overflow;
4171 requiredsize += insize - newpos;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004172 outsize = *bufsize;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004173 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004174 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004175 requiredsize = 2*outsize;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004176 if (widechar_resize(buf, bufsize, requiredsize) < 0) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004177 goto onError;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004178 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004179 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02004180 wcsncpy(*buf + *outpos, repwstr, repwlen);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004181 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004182 *endinpos = newpos;
4183 *inptr = *input + newpos;
4184
4185 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004186 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004187 return 0;
4188
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004189 overflow:
4190 PyErr_SetString(PyExc_OverflowError,
4191 "decoded result is too long for a Python string");
4192
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004193 onError:
4194 Py_XDECREF(restuple);
4195 return -1;
4196}
Steve Dowercc16be82016-09-08 10:35:16 -07004197#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004198
4199static int
4200unicode_decode_call_errorhandler_writer(
4201 const char *errors, PyObject **errorHandler,
4202 const char *encoding, const char *reason,
4203 const char **input, const char **inend, Py_ssize_t *startinpos,
4204 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4205 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4206{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004207 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004208
4209 PyObject *restuple = NULL;
4210 PyObject *repunicode = NULL;
4211 Py_ssize_t insize;
4212 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004213 Py_ssize_t replen;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004214 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004215 PyObject *inputobj = NULL;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004216 int need_to_grow = 0;
4217 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004218
4219 if (*errorHandler == NULL) {
4220 *errorHandler = PyCodec_LookupError(errors);
4221 if (*errorHandler == NULL)
4222 goto onError;
4223 }
4224
4225 make_decode_exception(exceptionObject,
4226 encoding,
4227 *input, *inend - *input,
4228 *startinpos, *endinpos,
4229 reason);
4230 if (*exceptionObject == NULL)
4231 goto onError;
4232
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004233 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004234 if (restuple == NULL)
4235 goto onError;
4236 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004237 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004238 goto onError;
4239 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004240 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004241 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004242
4243 /* Copy back the bytes variables, which might have been modified by the
4244 callback */
4245 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4246 if (!inputobj)
4247 goto onError;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004248 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004249 *input = PyBytes_AS_STRING(inputobj);
4250 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004251 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004252 /* we can DECREF safely, as the exception has another reference,
4253 so the object won't go away. */
4254 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004255
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004256 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004257 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004258 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004259 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004260 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004261 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004262
Victor Stinner170ca6f2013-04-18 00:25:28 +02004263 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004264 if (replen > 1) {
4265 writer->min_length += replen - 1;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004266 need_to_grow = 1;
4267 }
4268 new_inptr = *input + newpos;
4269 if (*inend - new_inptr > remain) {
4270 /* We don't know the decoding algorithm here so we make the worst
4271 assumption that one byte decodes to one unicode character.
4272 If unfortunately one byte could decode to more unicode characters,
4273 the decoder may write out-of-bound then. Is it possible for the
4274 algorithms using this function? */
4275 writer->min_length += *inend - new_inptr - remain;
4276 need_to_grow = 1;
4277 }
4278 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004279 writer->overallocate = 1;
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02004280 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004281 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4282 goto onError;
4283 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004284 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004285 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004286
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004287 *endinpos = newpos;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004288 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004289
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004290 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004291 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004292 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004293
Benjamin Peterson29060642009-01-31 22:14:21 +00004294 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004295 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004296 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004297}
4298
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004299/* --- UTF-7 Codec -------------------------------------------------------- */
4300
Antoine Pitrou244651a2009-05-04 18:56:13 +00004301/* See RFC2152 for details. We encode conservatively and decode liberally. */
4302
4303/* Three simple macros defining base-64. */
4304
4305/* Is c a base-64 character? */
4306
4307#define IS_BASE64(c) \
4308 (((c) >= 'A' && (c) <= 'Z') || \
4309 ((c) >= 'a' && (c) <= 'z') || \
4310 ((c) >= '0' && (c) <= '9') || \
4311 (c) == '+' || (c) == '/')
4312
4313/* given that c is a base-64 character, what is its base-64 value? */
4314
4315#define FROM_BASE64(c) \
4316 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4317 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4318 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4319 (c) == '+' ? 62 : 63)
4320
4321/* What is the base-64 character of the bottom 6 bits of n? */
4322
4323#define TO_BASE64(n) \
4324 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4325
4326/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4327 * decoded as itself. We are permissive on decoding; the only ASCII
4328 * byte not decoding to itself is the + which begins a base64
4329 * string. */
4330
4331#define DECODE_DIRECT(c) \
4332 ((c) <= 127 && (c) != '+')
4333
4334/* The UTF-7 encoder treats ASCII characters differently according to
4335 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4336 * the above). See RFC2152. This array identifies these different
4337 * sets:
4338 * 0 : "Set D"
4339 * alphanumeric and '(),-./:?
4340 * 1 : "Set O"
4341 * !"#$%&*;<=>@[]^_`{|}
4342 * 2 : "whitespace"
4343 * ht nl cr sp
4344 * 3 : special (must be base64 encoded)
4345 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4346 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004347
Tim Petersced69f82003-09-16 20:30:58 +00004348static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004349char utf7_category[128] = {
4350/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4351 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4352/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4353 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4354/* sp ! " # $ % & ' ( ) * + , - . / */
4355 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4356/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4357 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4358/* @ A B C D E F G H I J K L M N O */
4359 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4360/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4361 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4362/* ` a b c d e f g h i j k l m n o */
4363 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4364/* p q r s t u v w x y z { | } ~ del */
4365 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004366};
4367
Antoine Pitrou244651a2009-05-04 18:56:13 +00004368/* ENCODE_DIRECT: this character should be encoded as itself. The
4369 * answer depends on whether we are encoding set O as itself, and also
4370 * on whether we are encoding whitespace as itself. RFC2152 makes it
4371 * clear that the answers to these questions vary between
4372 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004373
Antoine Pitrou244651a2009-05-04 18:56:13 +00004374#define ENCODE_DIRECT(c, directO, directWS) \
4375 ((c) < 128 && (c) > 0 && \
4376 ((utf7_category[(c)] == 0) || \
4377 (directWS && (utf7_category[(c)] == 2)) || \
4378 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004379
Alexander Belopolsky40018472011-02-26 01:02:56 +00004380PyObject *
4381PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004382 Py_ssize_t size,
4383 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004384{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004385 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4386}
4387
Antoine Pitrou244651a2009-05-04 18:56:13 +00004388/* The decoder. The only state we preserve is our read position,
4389 * i.e. how many characters we have consumed. So if we end in the
4390 * middle of a shift sequence we have to back off the read position
4391 * and the output to the beginning of the sequence, otherwise we lose
4392 * all the shift state (seen bits, number of bits seen, high
4393 * surrogate). */
4394
Alexander Belopolsky40018472011-02-26 01:02:56 +00004395PyObject *
4396PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004397 Py_ssize_t size,
4398 const char *errors,
4399 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004400{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004401 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004402 Py_ssize_t startinpos;
4403 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004404 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004405 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004406 const char *errmsg = "";
4407 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004408 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004409 unsigned int base64bits = 0;
4410 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004411 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004412 PyObject *errorHandler = NULL;
4413 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004414
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004415 if (size == 0) {
4416 if (consumed)
4417 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004418 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004419 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004420
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004421 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004422 _PyUnicodeWriter_Init(&writer);
4423 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004424
4425 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004426 e = s + size;
4427
4428 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004429 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004430 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004431 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004432
Antoine Pitrou244651a2009-05-04 18:56:13 +00004433 if (inShift) { /* in a base-64 section */
4434 if (IS_BASE64(ch)) { /* consume a base-64 character */
4435 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4436 base64bits += 6;
4437 s++;
4438 if (base64bits >= 16) {
4439 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004440 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004441 base64bits -= 16;
4442 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004443 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004444 if (surrogate) {
4445 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004446 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4447 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004448 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004449 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004450 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004451 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004452 }
4453 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004454 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004455 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 }
4458 }
Victor Stinner551ac952011-11-29 22:58:13 +01004459 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004460 /* first surrogate */
4461 surrogate = outCh;
4462 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004463 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004464 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004465 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004466 }
4467 }
4468 }
4469 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004470 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004471 if (base64bits > 0) { /* left-over bits */
4472 if (base64bits >= 6) {
4473 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004474 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 errmsg = "partial character in shift sequence";
4476 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004478 else {
4479 /* Some bits remain; they should be zero */
4480 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004481 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004482 errmsg = "non-zero padding bits in shift sequence";
4483 goto utf7Error;
4484 }
4485 }
4486 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004487 if (surrogate && DECODE_DIRECT(ch)) {
4488 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4489 goto onError;
4490 }
4491 surrogate = 0;
4492 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004493 /* '-' is absorbed; other terminating
4494 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004495 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004496 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004497 }
4498 }
4499 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004500 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004501 s++; /* consume '+' */
4502 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004503 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004504 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004505 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506 }
Zackery Spytze349bf22018-08-18 22:43:38 -06004507 else if (s < e && !IS_BASE64(*s)) {
4508 s++;
4509 errmsg = "ill-formed sequence";
4510 goto utf7Error;
4511 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004512 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004513 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004514 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004515 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004516 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004517 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004518 }
4519 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004520 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004521 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004522 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004523 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004524 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004525 else {
4526 startinpos = s-starts;
4527 s++;
4528 errmsg = "unexpected special character";
4529 goto utf7Error;
4530 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004531 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004532utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004533 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004534 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004535 errors, &errorHandler,
4536 "utf7", errmsg,
4537 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004538 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004539 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004540 }
4541
Antoine Pitrou244651a2009-05-04 18:56:13 +00004542 /* end of string */
4543
4544 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4545 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004546 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004547 if (surrogate ||
4548 (base64bits >= 6) ||
4549 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004550 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004551 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004552 errors, &errorHandler,
4553 "utf7", "unterminated shift sequence",
4554 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004555 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004556 goto onError;
4557 if (s < e)
4558 goto restart;
4559 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004560 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004561
4562 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004563 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004564 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004565 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004566 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004567 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004568 writer.kind, writer.data, shiftOutStart);
4569 Py_XDECREF(errorHandler);
4570 Py_XDECREF(exc);
4571 _PyUnicodeWriter_Dealloc(&writer);
4572 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004573 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004574 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004575 }
4576 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004577 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004578 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004579 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004580
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004581 Py_XDECREF(errorHandler);
4582 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004583 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004584
Benjamin Peterson29060642009-01-31 22:14:21 +00004585 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004586 Py_XDECREF(errorHandler);
4587 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004588 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004589 return NULL;
4590}
4591
4592
Alexander Belopolsky40018472011-02-26 01:02:56 +00004593PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004594_PyUnicode_EncodeUTF7(PyObject *str,
4595 int base64SetO,
4596 int base64WhiteSpace,
4597 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004599 int kind;
4600 void *data;
4601 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004602 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004603 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004604 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004605 unsigned int base64bits = 0;
4606 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004607 char * out;
4608 char * start;
4609
Benjamin Petersonbac79492012-01-14 13:34:47 -05004610 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004611 return NULL;
4612 kind = PyUnicode_KIND(str);
4613 data = PyUnicode_DATA(str);
4614 len = PyUnicode_GET_LENGTH(str);
4615
4616 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004617 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004618
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004619 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004620 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004621 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004622 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004623 if (v == NULL)
4624 return NULL;
4625
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004626 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004627 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004628 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004629
Antoine Pitrou244651a2009-05-04 18:56:13 +00004630 if (inShift) {
4631 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4632 /* shifting out */
4633 if (base64bits) { /* output remaining bits */
4634 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4635 base64buffer = 0;
4636 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004637 }
4638 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004639 /* Characters not in the BASE64 set implicitly unshift the sequence
4640 so no '-' is required, except if the character is itself a '-' */
4641 if (IS_BASE64(ch) || ch == '-') {
4642 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004643 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 *out++ = (char) ch;
4645 }
4646 else {
4647 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004648 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004649 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004650 else { /* not in a shift sequence */
4651 if (ch == '+') {
4652 *out++ = '+';
4653 *out++ = '-';
4654 }
4655 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4656 *out++ = (char) ch;
4657 }
4658 else {
4659 *out++ = '+';
4660 inShift = 1;
4661 goto encode_char;
4662 }
4663 }
4664 continue;
4665encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004666 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004667 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004668
Antoine Pitrou244651a2009-05-04 18:56:13 +00004669 /* code first surrogate */
4670 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004671 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004672 while (base64bits >= 6) {
4673 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4674 base64bits -= 6;
4675 }
4676 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004677 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004678 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004679 base64bits += 16;
4680 base64buffer = (base64buffer << 16) | ch;
4681 while (base64bits >= 6) {
4682 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4683 base64bits -= 6;
4684 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004685 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004686 if (base64bits)
4687 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4688 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004689 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004690 if (_PyBytes_Resize(&v, out - start) < 0)
4691 return NULL;
4692 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004693}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004694PyObject *
4695PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4696 Py_ssize_t size,
4697 int base64SetO,
4698 int base64WhiteSpace,
4699 const char *errors)
4700{
4701 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004702 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004703 if (tmp == NULL)
4704 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004705 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004706 base64WhiteSpace, errors);
4707 Py_DECREF(tmp);
4708 return result;
4709}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004710
Antoine Pitrou244651a2009-05-04 18:56:13 +00004711#undef IS_BASE64
4712#undef FROM_BASE64
4713#undef TO_BASE64
4714#undef DECODE_DIRECT
4715#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004716
Guido van Rossumd57fd912000-03-10 22:53:23 +00004717/* --- UTF-8 Codec -------------------------------------------------------- */
4718
Alexander Belopolsky40018472011-02-26 01:02:56 +00004719PyObject *
4720PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004721 Py_ssize_t size,
4722 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004723{
Walter Dörwald69652032004-09-07 20:24:22 +00004724 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4725}
4726
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727#include "stringlib/asciilib.h"
4728#include "stringlib/codecs.h"
4729#include "stringlib/undef.h"
4730
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004731#include "stringlib/ucs1lib.h"
4732#include "stringlib/codecs.h"
4733#include "stringlib/undef.h"
4734
4735#include "stringlib/ucs2lib.h"
4736#include "stringlib/codecs.h"
4737#include "stringlib/undef.h"
4738
4739#include "stringlib/ucs4lib.h"
4740#include "stringlib/codecs.h"
4741#include "stringlib/undef.h"
4742
Antoine Pitrouab868312009-01-10 15:40:25 +00004743/* Mask to quickly check whether a C 'long' contains a
4744 non-ASCII, UTF8-encoded char. */
4745#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004746# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004747#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004748# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004749#else
4750# error C 'long' size should be either 4 or 8!
4751#endif
4752
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753static Py_ssize_t
4754ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004755{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004756 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004757 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004758
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004759 /*
4760 * Issue #17237: m68k is a bit different from most architectures in
4761 * that objects do not use "natural alignment" - for example, int and
4762 * long are only aligned at 2-byte boundaries. Therefore the assert()
4763 * won't work; also, tests have shown that skipping the "optimised
4764 * version" will even speed up m68k.
4765 */
4766#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004768 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4769 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004770 /* Fast path, see in STRINGLIB(utf8_decode) for
4771 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004772 /* Help allocation */
4773 const char *_p = p;
4774 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004775 while (_p < aligned_end) {
4776 unsigned long value = *(const unsigned long *) _p;
4777 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004778 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004779 *((unsigned long *)q) = value;
4780 _p += SIZEOF_LONG;
4781 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004782 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004783 p = _p;
4784 while (p < end) {
4785 if ((unsigned char)*p & 0x80)
4786 break;
4787 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004788 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004789 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004790 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004791#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004792#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004793 while (p < end) {
4794 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4795 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004796 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004797 /* Help allocation */
4798 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799 while (_p < aligned_end) {
4800 unsigned long value = *(unsigned long *) _p;
4801 if (value & ASCII_CHAR_MASK)
4802 break;
4803 _p += SIZEOF_LONG;
4804 }
4805 p = _p;
4806 if (_p == end)
4807 break;
4808 }
4809 if ((unsigned char)*p & 0x80)
4810 break;
4811 ++p;
4812 }
4813 memcpy(dest, start, p - start);
4814 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004815}
Antoine Pitrouab868312009-01-10 15:40:25 +00004816
Victor Stinner785938e2011-12-11 20:09:03 +01004817PyObject *
4818PyUnicode_DecodeUTF8Stateful(const char *s,
4819 Py_ssize_t size,
4820 const char *errors,
4821 Py_ssize_t *consumed)
4822{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004823 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004824 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004825 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004826
4827 Py_ssize_t startinpos;
4828 Py_ssize_t endinpos;
4829 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004830 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004831 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004832 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004833
4834 if (size == 0) {
4835 if (consumed)
4836 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004837 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004838 }
4839
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004840 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4841 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004842 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 *consumed = 1;
4844 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004845 }
4846
Victor Stinner8f674cc2013-04-17 23:02:17 +02004847 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004848 writer.min_length = size;
4849 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004850 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004851
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004852 writer.pos = ascii_decode(s, end, writer.data);
4853 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004854 while (s < end) {
4855 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004856 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004857
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004858 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004859 if (PyUnicode_IS_ASCII(writer.buffer))
4860 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004861 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004862 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004863 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004864 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004865 } else {
4866 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004867 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004868 }
4869
4870 switch (ch) {
4871 case 0:
4872 if (s == end || consumed)
4873 goto End;
4874 errmsg = "unexpected end of data";
4875 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004876 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004877 break;
4878 case 1:
4879 errmsg = "invalid start byte";
4880 startinpos = s - starts;
4881 endinpos = startinpos + 1;
4882 break;
4883 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004884 case 3:
4885 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004886 errmsg = "invalid continuation byte";
4887 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004888 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004889 break;
4890 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004891 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004892 goto onError;
4893 continue;
4894 }
4895
Victor Stinner1d65d912015-10-05 13:43:50 +02004896 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02004897 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner1d65d912015-10-05 13:43:50 +02004898
4899 switch (error_handler) {
4900 case _Py_ERROR_IGNORE:
4901 s += (endinpos - startinpos);
4902 break;
4903
4904 case _Py_ERROR_REPLACE:
4905 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4906 goto onError;
4907 s += (endinpos - startinpos);
4908 break;
4909
4910 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004911 {
4912 Py_ssize_t i;
4913
Victor Stinner1d65d912015-10-05 13:43:50 +02004914 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4915 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004916 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004917 ch = (Py_UCS4)(unsigned char)(starts[i]);
4918 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4919 ch + 0xdc00);
4920 writer.pos++;
4921 }
4922 s += (endinpos - startinpos);
4923 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004924 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004925
4926 default:
4927 if (unicode_decode_call_errorhandler_writer(
4928 errors, &error_handler_obj,
4929 "utf-8", errmsg,
4930 &starts, &end, &startinpos, &endinpos, &exc, &s,
4931 &writer))
4932 goto onError;
4933 }
Victor Stinner785938e2011-12-11 20:09:03 +01004934 }
4935
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004936End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004937 if (consumed)
4938 *consumed = s - starts;
4939
Victor Stinner1d65d912015-10-05 13:43:50 +02004940 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004941 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004942 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004943
4944onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004945 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004946 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004947 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004948 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004949}
4950
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004951
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004952/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4953 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004954
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004955 On success, write a pointer to a newly allocated wide character string into
4956 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4957 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004958
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004959 On memory allocation failure, return -1.
4960
4961 On decoding error (if surrogateescape is zero), return -2. If wlen is
4962 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4963 is not NULL, write the decoding error message into *reason. */
4964int
4965_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
Victor Stinner3d4226a2018-08-29 22:21:32 +02004966 const char **reason, _Py_error_handler errors)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004967{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004968 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004969 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004970 wchar_t *unicode;
4971 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004972
Victor Stinner3d4226a2018-08-29 22:21:32 +02004973 int surrogateescape = 0;
4974 int surrogatepass = 0;
4975 switch (errors)
4976 {
4977 case _Py_ERROR_STRICT:
4978 break;
4979 case _Py_ERROR_SURROGATEESCAPE:
4980 surrogateescape = 1;
4981 break;
4982 case _Py_ERROR_SURROGATEPASS:
4983 surrogatepass = 1;
4984 break;
4985 default:
4986 return -3;
4987 }
4988
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004989 /* Note: size will always be longer than the resulting Unicode
4990 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004991 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004992 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004993 }
4994
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004995 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004996 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004997 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004998 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004999
5000 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005001 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005002 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005003 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005004 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005005#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005006 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005007#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005008 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005009#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005010 if (ch > 0xFF) {
5011#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005012 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005013#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005014 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005015 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005016 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5017 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5018#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005019 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005020 else {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005021 if (!ch && s == e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005022 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005023 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005024
5025 if (surrogateescape) {
5026 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5027 }
5028 else {
5029 /* Is it a valid three-byte code? */
5030 if (surrogatepass
5031 && (e - s) >= 3
5032 && (s[0] & 0xf0) == 0xe0
5033 && (s[1] & 0xc0) == 0x80
5034 && (s[2] & 0xc0) == 0x80)
5035 {
5036 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5037 s += 3;
5038 unicode[outpos++] = ch;
5039 }
5040 else {
5041 PyMem_RawFree(unicode );
5042 if (reason != NULL) {
5043 switch (ch) {
5044 case 0:
5045 *reason = "unexpected end of data";
5046 break;
5047 case 1:
5048 *reason = "invalid start byte";
5049 break;
5050 /* 2, 3, 4 */
5051 default:
5052 *reason = "invalid continuation byte";
5053 break;
5054 }
5055 }
5056 if (wlen != NULL) {
5057 *wlen = s - orig_s;
5058 }
5059 return -2;
5060 }
5061 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005062 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005063 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005064 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005065 if (wlen) {
5066 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005067 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005068 *wstr = unicode;
5069 return 0;
5070}
5071
Victor Stinner5f9cf232019-03-19 01:46:25 +01005072
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005073wchar_t*
Victor Stinner5f9cf232019-03-19 01:46:25 +01005074_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
5075 size_t *wlen)
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005076{
5077 wchar_t *wstr;
Victor Stinner5f9cf232019-03-19 01:46:25 +01005078 int res = _Py_DecodeUTF8Ex(arg, arglen,
5079 &wstr, wlen,
5080 NULL, _Py_ERROR_SURROGATEESCAPE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005081 if (res != 0) {
Victor Stinner5f9cf232019-03-19 01:46:25 +01005082 /* _Py_DecodeUTF8Ex() must support _Py_ERROR_SURROGATEESCAPE */
5083 assert(res != -3);
5084 if (wlen) {
5085 *wlen = (size_t)res;
5086 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005087 return NULL;
5088 }
5089 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005090}
5091
Antoine Pitrouab868312009-01-10 15:40:25 +00005092
Victor Stinnere47e6982017-12-21 15:45:16 +01005093/* UTF-8 encoder using the surrogateescape error handler .
5094
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005095 On success, return 0 and write the newly allocated character string (use
5096 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005097
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005098 On encoding failure, return -2 and write the position of the invalid
5099 surrogate character into *error_pos (if error_pos is set) and the decoding
5100 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005101
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005102 On memory allocation failure, return -1. */
5103int
5104_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005105 const char **reason, int raw_malloc, _Py_error_handler errors)
Victor Stinnere47e6982017-12-21 15:45:16 +01005106{
5107 const Py_ssize_t max_char_size = 4;
5108 Py_ssize_t len = wcslen(text);
5109
5110 assert(len >= 0);
5111
Victor Stinner3d4226a2018-08-29 22:21:32 +02005112 int surrogateescape = 0;
5113 int surrogatepass = 0;
5114 switch (errors)
5115 {
5116 case _Py_ERROR_STRICT:
5117 break;
5118 case _Py_ERROR_SURROGATEESCAPE:
5119 surrogateescape = 1;
5120 break;
5121 case _Py_ERROR_SURROGATEPASS:
5122 surrogatepass = 1;
5123 break;
5124 default:
5125 return -3;
5126 }
5127
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005128 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5129 return -1;
5130 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005131 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005132 if (raw_malloc) {
5133 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005134 }
5135 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005136 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005137 }
5138 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005139 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005140 }
5141
5142 char *p = bytes;
5143 Py_ssize_t i;
Victor Stinner3d4226a2018-08-29 22:21:32 +02005144 for (i = 0; i < len; ) {
5145 Py_ssize_t ch_pos = i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005146 Py_UCS4 ch = text[i];
Victor Stinner3d4226a2018-08-29 22:21:32 +02005147 i++;
5148#if Py_UNICODE_SIZE == 2
5149 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
5150 && i < len
5151 && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5152 {
5153 ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5154 i++;
5155 }
5156#endif
Victor Stinnere47e6982017-12-21 15:45:16 +01005157
5158 if (ch < 0x80) {
5159 /* Encode ASCII */
5160 *p++ = (char) ch;
5161
5162 }
5163 else if (ch < 0x0800) {
5164 /* Encode Latin-1 */
5165 *p++ = (char)(0xc0 | (ch >> 6));
5166 *p++ = (char)(0x80 | (ch & 0x3f));
5167 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005168 else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005169 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005170 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005171 if (error_pos != NULL) {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005172 *error_pos = (size_t)ch_pos;
Victor Stinnere47e6982017-12-21 15:45:16 +01005173 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005174 if (reason != NULL) {
5175 *reason = "encoding error";
5176 }
5177 if (raw_malloc) {
5178 PyMem_RawFree(bytes);
5179 }
5180 else {
5181 PyMem_Free(bytes);
5182 }
5183 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005184 }
5185 *p++ = (char)(ch & 0xff);
5186 }
5187 else if (ch < 0x10000) {
5188 *p++ = (char)(0xe0 | (ch >> 12));
5189 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5190 *p++ = (char)(0x80 | (ch & 0x3f));
5191 }
5192 else { /* ch >= 0x10000 */
5193 assert(ch <= MAX_UNICODE);
5194 /* Encode UCS4 Unicode ordinals */
5195 *p++ = (char)(0xf0 | (ch >> 18));
5196 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5197 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5198 *p++ = (char)(0x80 | (ch & 0x3f));
5199 }
5200 }
5201 *p++ = '\0';
5202
5203 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005204 char *bytes2;
5205 if (raw_malloc) {
5206 bytes2 = PyMem_RawRealloc(bytes, final_size);
5207 }
5208 else {
5209 bytes2 = PyMem_Realloc(bytes, final_size);
5210 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005211 if (bytes2 == NULL) {
5212 if (error_pos != NULL) {
5213 *error_pos = (size_t)-1;
5214 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005215 if (raw_malloc) {
5216 PyMem_RawFree(bytes);
5217 }
5218 else {
5219 PyMem_Free(bytes);
5220 }
5221 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005222 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005223 *str = bytes2;
5224 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005225}
5226
5227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005228/* Primary internal function which creates utf8 encoded bytes objects.
5229
5230 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005231 and allocate exactly as much space needed at the end. Else allocate the
5232 maximum possible needed (4 result bytes per Unicode character), and return
5233 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005234*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005235PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005236_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005237{
Victor Stinner6099a032011-12-18 14:22:26 +01005238 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005239 void *data;
5240 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005242 if (!PyUnicode_Check(unicode)) {
5243 PyErr_BadArgument();
5244 return NULL;
5245 }
5246
5247 if (PyUnicode_READY(unicode) == -1)
5248 return NULL;
5249
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005250 if (PyUnicode_UTF8(unicode))
5251 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5252 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005253
5254 kind = PyUnicode_KIND(unicode);
5255 data = PyUnicode_DATA(unicode);
5256 size = PyUnicode_GET_LENGTH(unicode);
5257
Benjamin Petersonead6b532011-12-20 17:23:42 -06005258 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005259 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005260 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005261 case PyUnicode_1BYTE_KIND:
5262 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5263 assert(!PyUnicode_IS_ASCII(unicode));
5264 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5265 case PyUnicode_2BYTE_KIND:
5266 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5267 case PyUnicode_4BYTE_KIND:
5268 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005269 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005270}
5271
Alexander Belopolsky40018472011-02-26 01:02:56 +00005272PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005273PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5274 Py_ssize_t size,
5275 const char *errors)
5276{
5277 PyObject *v, *unicode;
5278
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005279 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005280 if (unicode == NULL)
5281 return NULL;
5282 v = _PyUnicode_AsUTF8String(unicode, errors);
5283 Py_DECREF(unicode);
5284 return v;
5285}
5286
5287PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005288PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005289{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005290 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005291}
5292
Walter Dörwald41980ca2007-08-16 21:55:45 +00005293/* --- UTF-32 Codec ------------------------------------------------------- */
5294
5295PyObject *
5296PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005297 Py_ssize_t size,
5298 const char *errors,
5299 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005300{
5301 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5302}
5303
5304PyObject *
5305PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005306 Py_ssize_t size,
5307 const char *errors,
5308 int *byteorder,
5309 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005310{
5311 const char *starts = s;
5312 Py_ssize_t startinpos;
5313 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005314 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005315 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005316 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005317 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005318 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005319 PyObject *errorHandler = NULL;
5320 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005321
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322 q = (unsigned char *)s;
5323 e = q + size;
5324
5325 if (byteorder)
5326 bo = *byteorder;
5327
5328 /* Check for BOM marks (U+FEFF) in the input and adjust current
5329 byte order setting accordingly. In native mode, the leading BOM
5330 mark is skipped, in all other modes, it is copied to the output
5331 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005332 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005333 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005334 if (bom == 0x0000FEFF) {
5335 bo = -1;
5336 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005337 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005338 else if (bom == 0xFFFE0000) {
5339 bo = 1;
5340 q += 4;
5341 }
5342 if (byteorder)
5343 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005344 }
5345
Victor Stinnere64322e2012-10-30 23:12:47 +01005346 if (q == e) {
5347 if (consumed)
5348 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005349 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005350 }
5351
Victor Stinnere64322e2012-10-30 23:12:47 +01005352#ifdef WORDS_BIGENDIAN
5353 le = bo < 0;
5354#else
5355 le = bo <= 0;
5356#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005357 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005358
Victor Stinner8f674cc2013-04-17 23:02:17 +02005359 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005360 writer.min_length = (e - q + 3) / 4;
5361 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005363
Victor Stinnere64322e2012-10-30 23:12:47 +01005364 while (1) {
5365 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005366 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005367
Victor Stinnere64322e2012-10-30 23:12:47 +01005368 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005369 enum PyUnicode_Kind kind = writer.kind;
5370 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005371 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005372 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005373 if (le) {
5374 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005375 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005376 if (ch > maxch)
5377 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005378 if (kind != PyUnicode_1BYTE_KIND &&
5379 Py_UNICODE_IS_SURROGATE(ch))
5380 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005381 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005382 q += 4;
5383 } while (q <= last);
5384 }
5385 else {
5386 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005387 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005388 if (ch > maxch)
5389 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005390 if (kind != PyUnicode_1BYTE_KIND &&
5391 Py_UNICODE_IS_SURROGATE(ch))
5392 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005393 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005394 q += 4;
5395 } while (q <= last);
5396 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005397 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005398 }
5399
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005400 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005401 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005402 startinpos = ((const char *)q) - starts;
5403 endinpos = startinpos + 4;
5404 }
5405 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005406 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005407 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005408 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005409 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005410 startinpos = ((const char *)q) - starts;
5411 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005412 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005413 else {
5414 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005415 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005416 goto onError;
5417 q += 4;
5418 continue;
5419 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005420 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005421 startinpos = ((const char *)q) - starts;
5422 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005423 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005424
5425 /* The remaining input chars are ignored if the callback
5426 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005427 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005428 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005429 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005430 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005431 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005433 }
5434
Walter Dörwald41980ca2007-08-16 21:55:45 +00005435 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005436 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005437
Walter Dörwald41980ca2007-08-16 21:55:45 +00005438 Py_XDECREF(errorHandler);
5439 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005440 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005441
Benjamin Peterson29060642009-01-31 22:14:21 +00005442 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005443 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005444 Py_XDECREF(errorHandler);
5445 Py_XDECREF(exc);
5446 return NULL;
5447}
5448
5449PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005450_PyUnicode_EncodeUTF32(PyObject *str,
5451 const char *errors,
5452 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005453{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005454 enum PyUnicode_Kind kind;
5455 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005456 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005457 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005458 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005459#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005460 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005461#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005462 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005463#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005464 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005465 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005466 PyObject *errorHandler = NULL;
5467 PyObject *exc = NULL;
5468 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005469
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005470 if (!PyUnicode_Check(str)) {
5471 PyErr_BadArgument();
5472 return NULL;
5473 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005474 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005475 return NULL;
5476 kind = PyUnicode_KIND(str);
5477 data = PyUnicode_DATA(str);
5478 len = PyUnicode_GET_LENGTH(str);
5479
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005480 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005481 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005482 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005483 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005484 if (v == NULL)
5485 return NULL;
5486
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005487 /* output buffer is 4-bytes aligned */
5488 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005489 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005490 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005491 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005492 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005493 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005494
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005495 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005496 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005497 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005498 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005499 else
5500 encoding = "utf-32";
5501
5502 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005503 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5504 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005505 }
5506
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005507 pos = 0;
5508 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005509 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005510
5511 if (kind == PyUnicode_2BYTE_KIND) {
5512 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5513 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005514 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005515 else {
5516 assert(kind == PyUnicode_4BYTE_KIND);
5517 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5518 &out, native_ordering);
5519 }
5520 if (pos == len)
5521 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005522
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005523 rep = unicode_encode_call_errorhandler(
5524 errors, &errorHandler,
5525 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005526 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005527 if (!rep)
5528 goto error;
5529
5530 if (PyBytes_Check(rep)) {
5531 repsize = PyBytes_GET_SIZE(rep);
5532 if (repsize & 3) {
5533 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005534 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005535 "surrogates not allowed");
5536 goto error;
5537 }
5538 moreunits = repsize / 4;
5539 }
5540 else {
5541 assert(PyUnicode_Check(rep));
5542 if (PyUnicode_READY(rep) < 0)
5543 goto error;
5544 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5545 if (!PyUnicode_IS_ASCII(rep)) {
5546 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005547 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005548 "surrogates not allowed");
5549 goto error;
5550 }
5551 }
5552
5553 /* four bytes are reserved for each surrogate */
5554 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005555 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005556 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005557 /* integer overflow */
5558 PyErr_NoMemory();
5559 goto error;
5560 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005561 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005562 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005563 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005564 }
5565
5566 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005567 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005568 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005569 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005570 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005571 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5572 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005573 }
5574
5575 Py_CLEAR(rep);
5576 }
5577
5578 /* Cut back to size actually needed. This is necessary for, for example,
5579 encoding of a string containing isolated surrogates and the 'ignore'
5580 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005581 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005582 if (nsize != PyBytes_GET_SIZE(v))
5583 _PyBytes_Resize(&v, nsize);
5584 Py_XDECREF(errorHandler);
5585 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005586 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005587 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005588 error:
5589 Py_XDECREF(rep);
5590 Py_XDECREF(errorHandler);
5591 Py_XDECREF(exc);
5592 Py_XDECREF(v);
5593 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005594}
5595
Alexander Belopolsky40018472011-02-26 01:02:56 +00005596PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005597PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5598 Py_ssize_t size,
5599 const char *errors,
5600 int byteorder)
5601{
5602 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005603 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005604 if (tmp == NULL)
5605 return NULL;
5606 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5607 Py_DECREF(tmp);
5608 return result;
5609}
5610
5611PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005612PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005613{
Victor Stinnerb960b342011-11-20 19:12:52 +01005614 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005615}
5616
Guido van Rossumd57fd912000-03-10 22:53:23 +00005617/* --- UTF-16 Codec ------------------------------------------------------- */
5618
Tim Peters772747b2001-08-09 22:21:55 +00005619PyObject *
5620PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005621 Py_ssize_t size,
5622 const char *errors,
5623 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005624{
Walter Dörwald69652032004-09-07 20:24:22 +00005625 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5626}
5627
5628PyObject *
5629PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005630 Py_ssize_t size,
5631 const char *errors,
5632 int *byteorder,
5633 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005634{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005635 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005636 Py_ssize_t startinpos;
5637 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005638 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005639 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005640 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005641 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005642 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005643 PyObject *errorHandler = NULL;
5644 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005645 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005646
Tim Peters772747b2001-08-09 22:21:55 +00005647 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005648 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649
5650 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005651 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005653 /* Check for BOM marks (U+FEFF) in the input and adjust current
5654 byte order setting accordingly. In native mode, the leading BOM
5655 mark is skipped, in all other modes, it is copied to the output
5656 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005657 if (bo == 0 && size >= 2) {
5658 const Py_UCS4 bom = (q[1] << 8) | q[0];
5659 if (bom == 0xFEFF) {
5660 q += 2;
5661 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005662 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005663 else if (bom == 0xFFFE) {
5664 q += 2;
5665 bo = 1;
5666 }
5667 if (byteorder)
5668 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005669 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670
Antoine Pitrou63065d72012-05-15 23:48:04 +02005671 if (q == e) {
5672 if (consumed)
5673 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005674 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005675 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005676
Christian Heimes743e0cd2012-10-17 23:52:17 +02005677#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005678 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005679 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005680#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005681 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005682 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005683#endif
Tim Peters772747b2001-08-09 22:21:55 +00005684
Antoine Pitrou63065d72012-05-15 23:48:04 +02005685 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005686 character count normally. Error handler will take care of
5687 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005688 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005689 writer.min_length = (e - q + 1) / 2;
5690 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005691 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005692
Antoine Pitrou63065d72012-05-15 23:48:04 +02005693 while (1) {
5694 Py_UCS4 ch = 0;
5695 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005696 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005697 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005698 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005699 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005700 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005701 native_ordering);
5702 else
5703 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005704 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005705 native_ordering);
5706 } else if (kind == PyUnicode_2BYTE_KIND) {
5707 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005708 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005709 native_ordering);
5710 } else {
5711 assert(kind == PyUnicode_4BYTE_KIND);
5712 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005713 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005714 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005715 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005716 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005717
Antoine Pitrou63065d72012-05-15 23:48:04 +02005718 switch (ch)
5719 {
5720 case 0:
5721 /* remaining byte at the end? (size should be even) */
5722 if (q == e || consumed)
5723 goto End;
5724 errmsg = "truncated data";
5725 startinpos = ((const char *)q) - starts;
5726 endinpos = ((const char *)e) - starts;
5727 break;
5728 /* The remaining input chars are ignored if the callback
5729 chooses to skip the input */
5730 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005731 q -= 2;
5732 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005733 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005734 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005735 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005736 endinpos = ((const char *)e) - starts;
5737 break;
5738 case 2:
5739 errmsg = "illegal encoding";
5740 startinpos = ((const char *)q) - 2 - starts;
5741 endinpos = startinpos + 2;
5742 break;
5743 case 3:
5744 errmsg = "illegal UTF-16 surrogate";
5745 startinpos = ((const char *)q) - 4 - starts;
5746 endinpos = startinpos + 2;
5747 break;
5748 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005749 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005750 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005751 continue;
5752 }
5753
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005754 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005755 errors,
5756 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005757 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005758 &starts,
5759 (const char **)&e,
5760 &startinpos,
5761 &endinpos,
5762 &exc,
5763 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005764 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005765 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005766 }
5767
Antoine Pitrou63065d72012-05-15 23:48:04 +02005768End:
Walter Dörwald69652032004-09-07 20:24:22 +00005769 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005770 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005771
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005772 Py_XDECREF(errorHandler);
5773 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005774 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005775
Benjamin Peterson29060642009-01-31 22:14:21 +00005776 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005777 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005778 Py_XDECREF(errorHandler);
5779 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005780 return NULL;
5781}
5782
Tim Peters772747b2001-08-09 22:21:55 +00005783PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005784_PyUnicode_EncodeUTF16(PyObject *str,
5785 const char *errors,
5786 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005787{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005788 enum PyUnicode_Kind kind;
5789 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005790 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005791 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005792 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005793 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005794#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005795 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005796#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005797 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005798#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005799 const char *encoding;
5800 Py_ssize_t nsize, pos;
5801 PyObject *errorHandler = NULL;
5802 PyObject *exc = NULL;
5803 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005804
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005805 if (!PyUnicode_Check(str)) {
5806 PyErr_BadArgument();
5807 return NULL;
5808 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005809 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005810 return NULL;
5811 kind = PyUnicode_KIND(str);
5812 data = PyUnicode_DATA(str);
5813 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005814
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005815 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005816 if (kind == PyUnicode_4BYTE_KIND) {
5817 const Py_UCS4 *in = (const Py_UCS4 *)data;
5818 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005819 while (in < end) {
5820 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005821 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005822 }
5823 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005824 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005825 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005826 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005827 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005828 nsize = len + pairs + (byteorder == 0);
5829 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005830 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005831 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005832 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005833
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005834 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005835 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005836 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005837 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005838 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005839 }
5840 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005841 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005842 }
Tim Peters772747b2001-08-09 22:21:55 +00005843
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005844 if (kind == PyUnicode_1BYTE_KIND) {
5845 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5846 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005847 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005848
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005849 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005850 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005851 }
5852 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005853 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005854 }
5855 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005856 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005857 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005858
5859 pos = 0;
5860 while (pos < len) {
5861 Py_ssize_t repsize, moreunits;
5862
5863 if (kind == PyUnicode_2BYTE_KIND) {
5864 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5865 &out, native_ordering);
5866 }
5867 else {
5868 assert(kind == PyUnicode_4BYTE_KIND);
5869 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5870 &out, native_ordering);
5871 }
5872 if (pos == len)
5873 break;
5874
5875 rep = unicode_encode_call_errorhandler(
5876 errors, &errorHandler,
5877 encoding, "surrogates not allowed",
5878 str, &exc, pos, pos + 1, &pos);
5879 if (!rep)
5880 goto error;
5881
5882 if (PyBytes_Check(rep)) {
5883 repsize = PyBytes_GET_SIZE(rep);
5884 if (repsize & 1) {
5885 raise_encode_exception(&exc, encoding,
5886 str, pos - 1, pos,
5887 "surrogates not allowed");
5888 goto error;
5889 }
5890 moreunits = repsize / 2;
5891 }
5892 else {
5893 assert(PyUnicode_Check(rep));
5894 if (PyUnicode_READY(rep) < 0)
5895 goto error;
5896 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5897 if (!PyUnicode_IS_ASCII(rep)) {
5898 raise_encode_exception(&exc, encoding,
5899 str, pos - 1, pos,
5900 "surrogates not allowed");
5901 goto error;
5902 }
5903 }
5904
5905 /* two bytes are reserved for each surrogate */
5906 if (moreunits > 1) {
5907 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005908 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005909 /* integer overflow */
5910 PyErr_NoMemory();
5911 goto error;
5912 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005913 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005914 goto error;
5915 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5916 }
5917
5918 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005919 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005920 out += moreunits;
5921 } else /* rep is unicode */ {
5922 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5923 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5924 &out, native_ordering);
5925 }
5926
5927 Py_CLEAR(rep);
5928 }
5929
5930 /* Cut back to size actually needed. This is necessary for, for example,
5931 encoding of a string containing isolated surrogates and the 'ignore' handler
5932 is used. */
5933 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5934 if (nsize != PyBytes_GET_SIZE(v))
5935 _PyBytes_Resize(&v, nsize);
5936 Py_XDECREF(errorHandler);
5937 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005938 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005939 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005940 error:
5941 Py_XDECREF(rep);
5942 Py_XDECREF(errorHandler);
5943 Py_XDECREF(exc);
5944 Py_XDECREF(v);
5945 return NULL;
5946#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005947}
5948
Alexander Belopolsky40018472011-02-26 01:02:56 +00005949PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005950PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5951 Py_ssize_t size,
5952 const char *errors,
5953 int byteorder)
5954{
5955 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005956 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005957 if (tmp == NULL)
5958 return NULL;
5959 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5960 Py_DECREF(tmp);
5961 return result;
5962}
5963
5964PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005965PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005967 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968}
5969
5970/* --- Unicode Escape Codec ----------------------------------------------- */
5971
Fredrik Lundh06d12682001-01-24 07:59:11 +00005972static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005973
Alexander Belopolsky40018472011-02-26 01:02:56 +00005974PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005975_PyUnicode_DecodeUnicodeEscape(const char *s,
5976 Py_ssize_t size,
5977 const char *errors,
5978 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005979{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005980 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005981 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005983 PyObject *errorHandler = NULL;
5984 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005985
Eric V. Smith42454af2016-10-31 09:22:08 -04005986 // so we can remember if we've seen an invalid escape char or not
5987 *first_invalid_escape = NULL;
5988
Victor Stinner62ec3312016-09-06 17:04:34 -07005989 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005990 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005991 }
5992 /* Escaped strings will always be longer than the resulting
5993 Unicode string, so we start with size here and then reduce the
5994 length after conversion to the true value.
5995 (but if the error callback returns a long replacement string
5996 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005997 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005998 writer.min_length = size;
5999 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6000 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006001 }
6002
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003 end = s + size;
6004 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006005 unsigned char c = (unsigned char) *s++;
6006 Py_UCS4 ch;
6007 int count;
6008 Py_ssize_t startinpos;
6009 Py_ssize_t endinpos;
6010 const char *message;
6011
6012#define WRITE_ASCII_CHAR(ch) \
6013 do { \
6014 assert(ch <= 127); \
6015 assert(writer.pos < writer.size); \
6016 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6017 } while(0)
6018
6019#define WRITE_CHAR(ch) \
6020 do { \
6021 if (ch <= writer.maxchar) { \
6022 assert(writer.pos < writer.size); \
6023 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6024 } \
6025 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6026 goto onError; \
6027 } \
6028 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029
6030 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006031 if (c != '\\') {
6032 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 continue;
6034 }
6035
Victor Stinner62ec3312016-09-06 17:04:34 -07006036 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006038 if (s >= end) {
6039 message = "\\ at end of string";
6040 goto error;
6041 }
6042 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006043
Victor Stinner62ec3312016-09-06 17:04:34 -07006044 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006045 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006046
Benjamin Peterson29060642009-01-31 22:14:21 +00006047 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006048 case '\n': continue;
6049 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6050 case '\'': WRITE_ASCII_CHAR('\''); continue;
6051 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6052 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006053 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006054 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6055 case 't': WRITE_ASCII_CHAR('\t'); continue;
6056 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6057 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006058 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006059 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006060 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006061 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062
Benjamin Peterson29060642009-01-31 22:14:21 +00006063 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006064 case '0': case '1': case '2': case '3':
6065 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006066 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006067 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006068 ch = (ch<<3) + *s++ - '0';
6069 if (s < end && '0' <= *s && *s <= '7') {
6070 ch = (ch<<3) + *s++ - '0';
6071 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006073 WRITE_CHAR(ch);
6074 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075
Benjamin Peterson29060642009-01-31 22:14:21 +00006076 /* hex escapes */
6077 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006079 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006080 message = "truncated \\xXX escape";
6081 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082
Benjamin Peterson29060642009-01-31 22:14:21 +00006083 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006084 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006085 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006086 message = "truncated \\uXXXX escape";
6087 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006090 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006091 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006092 message = "truncated \\UXXXXXXXX escape";
6093 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006094 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006095 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006096 ch <<= 4;
6097 if (c >= '0' && c <= '9') {
6098 ch += c - '0';
6099 }
6100 else if (c >= 'a' && c <= 'f') {
6101 ch += c - ('a' - 10);
6102 }
6103 else if (c >= 'A' && c <= 'F') {
6104 ch += c - ('A' - 10);
6105 }
6106 else {
6107 break;
6108 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006109 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006110 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006111 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006112 }
6113
6114 /* when we get here, ch is a 32-bit unicode character */
6115 if (ch > MAX_UNICODE) {
6116 message = "illegal Unicode character";
6117 goto error;
6118 }
6119
6120 WRITE_CHAR(ch);
6121 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006122
Benjamin Peterson29060642009-01-31 22:14:21 +00006123 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006124 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006125 if (ucnhash_CAPI == NULL) {
6126 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006127 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6128 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006129 if (ucnhash_CAPI == NULL) {
6130 PyErr_SetString(
6131 PyExc_UnicodeError,
6132 "\\N escapes not supported (can't load unicodedata module)"
6133 );
6134 goto onError;
6135 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006136 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006137
6138 message = "malformed \\N character escape";
Gregory P. Smith746b2d32018-11-13 13:16:54 -08006139 if (s < end && *s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006140 const char *start = ++s;
6141 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006142 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006143 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006144 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006145 namelen = s - start;
6146 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006147 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006148 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006149 ch = 0xffffffff; /* in case 'getcode' messes up */
6150 if (namelen <= INT_MAX &&
6151 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6152 &ch, 0)) {
6153 assert(ch <= MAX_UNICODE);
6154 WRITE_CHAR(ch);
6155 continue;
6156 }
6157 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006158 }
6159 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006160 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006161
6162 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006163 if (*first_invalid_escape == NULL) {
6164 *first_invalid_escape = s-1; /* Back up one char, since we've
6165 already incremented s. */
6166 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006167 WRITE_ASCII_CHAR('\\');
6168 WRITE_CHAR(c);
6169 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006170 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006171
6172 error:
6173 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006174 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006175 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006176 errors, &errorHandler,
6177 "unicodeescape", message,
6178 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006179 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006180 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006181 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006182 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006183
6184#undef WRITE_ASCII_CHAR
6185#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006187
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006188 Py_XDECREF(errorHandler);
6189 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006190 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006191
Benjamin Peterson29060642009-01-31 22:14:21 +00006192 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006193 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006194 Py_XDECREF(errorHandler);
6195 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006196 return NULL;
6197}
6198
Eric V. Smith42454af2016-10-31 09:22:08 -04006199PyObject *
6200PyUnicode_DecodeUnicodeEscape(const char *s,
6201 Py_ssize_t size,
6202 const char *errors)
6203{
6204 const char *first_invalid_escape;
6205 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6206 &first_invalid_escape);
6207 if (result == NULL)
6208 return NULL;
6209 if (first_invalid_escape != NULL) {
6210 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6211 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006212 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006213 Py_DECREF(result);
6214 return NULL;
6215 }
6216 }
6217 return result;
6218}
6219
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006220/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221
Alexander Belopolsky40018472011-02-26 01:02:56 +00006222PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006223PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006225 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006226 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006228 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006229 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006230 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231
Ezio Melottie7f90372012-10-05 03:33:31 +03006232 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006233 escape.
6234
Ezio Melottie7f90372012-10-05 03:33:31 +03006235 For UCS1 strings it's '\xxx', 4 bytes per source character.
6236 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6237 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006238 */
6239
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006240 if (!PyUnicode_Check(unicode)) {
6241 PyErr_BadArgument();
6242 return NULL;
6243 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006244 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006245 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006246 }
Victor Stinner358af132015-10-12 22:36:57 +02006247
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006248 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 if (len == 0) {
6250 return PyBytes_FromStringAndSize(NULL, 0);
6251 }
6252
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006253 kind = PyUnicode_KIND(unicode);
6254 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006255 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6256 bytes, and 1 byte characters 4. */
6257 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006258 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006259 return PyErr_NoMemory();
6260 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006261 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006262 if (repr == NULL) {
6263 return NULL;
6264 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006265
Victor Stinner62ec3312016-09-06 17:04:34 -07006266 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006267 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006268 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006269
Victor Stinner62ec3312016-09-06 17:04:34 -07006270 /* U+0000-U+00ff range */
6271 if (ch < 0x100) {
6272 if (ch >= ' ' && ch < 127) {
6273 if (ch != '\\') {
6274 /* Copy printable US ASCII as-is */
6275 *p++ = (char) ch;
6276 }
6277 /* Escape backslashes */
6278 else {
6279 *p++ = '\\';
6280 *p++ = '\\';
6281 }
6282 }
Victor Stinner358af132015-10-12 22:36:57 +02006283
Victor Stinner62ec3312016-09-06 17:04:34 -07006284 /* Map special whitespace to '\t', \n', '\r' */
6285 else if (ch == '\t') {
6286 *p++ = '\\';
6287 *p++ = 't';
6288 }
6289 else if (ch == '\n') {
6290 *p++ = '\\';
6291 *p++ = 'n';
6292 }
6293 else if (ch == '\r') {
6294 *p++ = '\\';
6295 *p++ = 'r';
6296 }
6297
6298 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6299 else {
6300 *p++ = '\\';
6301 *p++ = 'x';
6302 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6303 *p++ = Py_hexdigits[ch & 0x000F];
6304 }
Tim Petersced69f82003-09-16 20:30:58 +00006305 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006306 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006307 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308 *p++ = '\\';
6309 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006310 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6311 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6312 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6313 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006314 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006315 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6316 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006317
Victor Stinner62ec3312016-09-06 17:04:34 -07006318 /* Make sure that the first two digits are zero */
6319 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006320 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006321 *p++ = 'U';
6322 *p++ = '0';
6323 *p++ = '0';
6324 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6325 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6326 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6327 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6328 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6329 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006330 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006331 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006332
Victor Stinner62ec3312016-09-06 17:04:34 -07006333 assert(p - PyBytes_AS_STRING(repr) > 0);
6334 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6335 return NULL;
6336 }
6337 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006338}
6339
Alexander Belopolsky40018472011-02-26 01:02:56 +00006340PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006341PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6342 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006343{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006344 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006345 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006346 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006347 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006348 }
6349
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006350 result = PyUnicode_AsUnicodeEscapeString(tmp);
6351 Py_DECREF(tmp);
6352 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006353}
6354
6355/* --- Raw Unicode Escape Codec ------------------------------------------- */
6356
Alexander Belopolsky40018472011-02-26 01:02:56 +00006357PyObject *
6358PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006359 Py_ssize_t size,
6360 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006361{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006362 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006363 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006364 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006365 PyObject *errorHandler = NULL;
6366 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006367
Victor Stinner62ec3312016-09-06 17:04:34 -07006368 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006369 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006370 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006371
Guido van Rossumd57fd912000-03-10 22:53:23 +00006372 /* Escaped strings will always be longer than the resulting
6373 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006374 length after conversion to the true value. (But decoding error
6375 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006376 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006377 writer.min_length = size;
6378 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6379 goto onError;
6380 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006381
Guido van Rossumd57fd912000-03-10 22:53:23 +00006382 end = s + size;
6383 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006384 unsigned char c = (unsigned char) *s++;
6385 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006386 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006387 Py_ssize_t startinpos;
6388 Py_ssize_t endinpos;
6389 const char *message;
6390
6391#define WRITE_CHAR(ch) \
6392 do { \
6393 if (ch <= writer.maxchar) { \
6394 assert(writer.pos < writer.size); \
6395 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6396 } \
6397 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6398 goto onError; \
6399 } \
6400 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006401
Benjamin Peterson29060642009-01-31 22:14:21 +00006402 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006403 if (c != '\\' || s >= end) {
6404 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006406 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006407
Victor Stinner62ec3312016-09-06 17:04:34 -07006408 c = (unsigned char) *s++;
6409 if (c == 'u') {
6410 count = 4;
6411 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006412 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006413 else if (c == 'U') {
6414 count = 8;
6415 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006416 }
6417 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006418 assert(writer.pos < writer.size);
6419 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6420 WRITE_CHAR(c);
6421 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006422 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006423 startinpos = s - starts - 2;
6424
6425 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6426 for (ch = 0; count && s < end; ++s, --count) {
6427 c = (unsigned char)*s;
6428 ch <<= 4;
6429 if (c >= '0' && c <= '9') {
6430 ch += c - '0';
6431 }
6432 else if (c >= 'a' && c <= 'f') {
6433 ch += c - ('a' - 10);
6434 }
6435 else if (c >= 'A' && c <= 'F') {
6436 ch += c - ('A' - 10);
6437 }
6438 else {
6439 break;
6440 }
6441 }
6442 if (!count) {
6443 if (ch <= MAX_UNICODE) {
6444 WRITE_CHAR(ch);
6445 continue;
6446 }
6447 message = "\\Uxxxxxxxx out of range";
6448 }
6449
6450 endinpos = s-starts;
6451 writer.min_length = end - s + writer.pos;
6452 if (unicode_decode_call_errorhandler_writer(
6453 errors, &errorHandler,
6454 "rawunicodeescape", message,
6455 &starts, &end, &startinpos, &endinpos, &exc, &s,
6456 &writer)) {
6457 goto onError;
6458 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006459 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006460
6461#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006462 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006463 Py_XDECREF(errorHandler);
6464 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006465 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006466
Benjamin Peterson29060642009-01-31 22:14:21 +00006467 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006468 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 Py_XDECREF(errorHandler);
6470 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006471 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006472
Guido van Rossumd57fd912000-03-10 22:53:23 +00006473}
6474
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006475
Alexander Belopolsky40018472011-02-26 01:02:56 +00006476PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006477PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006478{
Victor Stinner62ec3312016-09-06 17:04:34 -07006479 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006480 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006481 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006482 int kind;
6483 void *data;
6484 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006485
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006486 if (!PyUnicode_Check(unicode)) {
6487 PyErr_BadArgument();
6488 return NULL;
6489 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006490 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006491 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006492 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006493 kind = PyUnicode_KIND(unicode);
6494 data = PyUnicode_DATA(unicode);
6495 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006496 if (kind == PyUnicode_1BYTE_KIND) {
6497 return PyBytes_FromStringAndSize(data, len);
6498 }
Victor Stinner0e368262011-11-10 20:12:49 +01006499
Victor Stinner62ec3312016-09-06 17:04:34 -07006500 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6501 bytes, and 1 byte characters 4. */
6502 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006503
Victor Stinner62ec3312016-09-06 17:04:34 -07006504 if (len > PY_SSIZE_T_MAX / expandsize) {
6505 return PyErr_NoMemory();
6506 }
6507 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6508 if (repr == NULL) {
6509 return NULL;
6510 }
6511 if (len == 0) {
6512 return repr;
6513 }
6514
6515 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006516 for (pos = 0; pos < len; pos++) {
6517 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006518
Victor Stinner62ec3312016-09-06 17:04:34 -07006519 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6520 if (ch < 0x100) {
6521 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006522 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006523 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006524 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006525 *p++ = '\\';
6526 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006527 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6528 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6529 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6530 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006531 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006532 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6533 else {
6534 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6535 *p++ = '\\';
6536 *p++ = 'U';
6537 *p++ = '0';
6538 *p++ = '0';
6539 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6540 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6541 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6542 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6543 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6544 *p++ = Py_hexdigits[ch & 15];
6545 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006546 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006547
Victor Stinner62ec3312016-09-06 17:04:34 -07006548 assert(p > PyBytes_AS_STRING(repr));
6549 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6550 return NULL;
6551 }
6552 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006553}
6554
Alexander Belopolsky40018472011-02-26 01:02:56 +00006555PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006556PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6557 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006558{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006559 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006560 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006561 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006562 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006563 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6564 Py_DECREF(tmp);
6565 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006566}
6567
6568/* --- Latin-1 Codec ------------------------------------------------------ */
6569
Alexander Belopolsky40018472011-02-26 01:02:56 +00006570PyObject *
6571PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006572 Py_ssize_t size,
6573 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006574{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006575 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006576 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006577}
6578
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006579/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006580static void
6581make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006582 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006583 PyObject *unicode,
6584 Py_ssize_t startpos, Py_ssize_t endpos,
6585 const char *reason)
6586{
6587 if (*exceptionObject == NULL) {
6588 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006589 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006590 encoding, unicode, startpos, endpos, reason);
6591 }
6592 else {
6593 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6594 goto onError;
6595 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6596 goto onError;
6597 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6598 goto onError;
6599 return;
6600 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006601 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006602 }
6603}
6604
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006605/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006606static void
6607raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006608 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006609 PyObject *unicode,
6610 Py_ssize_t startpos, Py_ssize_t endpos,
6611 const char *reason)
6612{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006613 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006614 encoding, unicode, startpos, endpos, reason);
6615 if (*exceptionObject != NULL)
6616 PyCodec_StrictErrors(*exceptionObject);
6617}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006618
6619/* error handling callback helper:
6620 build arguments, call the callback and check the arguments,
6621 put the result into newpos and return the replacement string, which
6622 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006623static PyObject *
6624unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006625 PyObject **errorHandler,
6626 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006627 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006628 Py_ssize_t startpos, Py_ssize_t endpos,
6629 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006630{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006631 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006632 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006633 PyObject *restuple;
6634 PyObject *resunicode;
6635
6636 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006637 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006638 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006639 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006640 }
6641
Benjamin Petersonbac79492012-01-14 13:34:47 -05006642 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 return NULL;
6644 len = PyUnicode_GET_LENGTH(unicode);
6645
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006646 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006648 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006649 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006650
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006651 restuple = PyObject_CallFunctionObjArgs(
6652 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006654 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006655 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006656 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 Py_DECREF(restuple);
6658 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006660 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006661 &resunicode, newpos)) {
6662 Py_DECREF(restuple);
6663 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006664 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006665 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6666 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6667 Py_DECREF(restuple);
6668 return NULL;
6669 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006670 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006671 *newpos = len + *newpos;
6672 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006673 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 Py_DECREF(restuple);
6675 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006676 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006677 Py_INCREF(resunicode);
6678 Py_DECREF(restuple);
6679 return resunicode;
6680}
6681
Alexander Belopolsky40018472011-02-26 01:02:56 +00006682static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006683unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006684 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006685 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006687 /* input state */
6688 Py_ssize_t pos=0, size;
6689 int kind;
6690 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006691 /* pointer into the output */
6692 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006693 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6694 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006695 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006696 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006697 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006698 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006699 /* output object */
6700 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006701
Benjamin Petersonbac79492012-01-14 13:34:47 -05006702 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006703 return NULL;
6704 size = PyUnicode_GET_LENGTH(unicode);
6705 kind = PyUnicode_KIND(unicode);
6706 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707 /* allocate enough for a simple encoding without
6708 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006709 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006710 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006711
6712 _PyBytesWriter_Init(&writer);
6713 str = _PyBytesWriter_Alloc(&writer, size);
6714 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006715 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006717 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006718 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006719
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006721 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006723 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006724 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006725 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006727 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006729 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006730 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006732
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006733 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006735
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006736 /* Only overallocate the buffer if it's not the last write */
6737 writer.overallocate = (collend < size);
6738
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006740 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006741 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02006742
6743 switch (error_handler) {
6744 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006745 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006746 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006747
6748 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006749 memset(str, '?', collend - collstart);
6750 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006751 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006752 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006753 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006754 break;
Victor Stinner50149202015-09-22 00:26:54 +02006755
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006756 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006757 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006758 writer.min_size -= (collend - collstart);
6759 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006760 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006761 if (str == NULL)
6762 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006763 pos = collend;
6764 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006765
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006766 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006767 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006768 writer.min_size -= (collend - collstart);
6769 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006770 unicode, collstart, collend);
6771 if (str == NULL)
6772 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006773 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 break;
Victor Stinner50149202015-09-22 00:26:54 +02006775
Victor Stinnerc3713e92015-09-29 12:32:13 +02006776 case _Py_ERROR_SURROGATEESCAPE:
6777 for (i = collstart; i < collend; ++i) {
6778 ch = PyUnicode_READ(kind, data, i);
6779 if (ch < 0xdc80 || 0xdcff < ch) {
6780 /* Not a UTF-8b surrogate */
6781 break;
6782 }
6783 *str++ = (char)(ch - 0xdc00);
6784 ++pos;
6785 }
6786 if (i >= collend)
6787 break;
6788 collstart = pos;
6789 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006790 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006791
Benjamin Peterson29060642009-01-31 22:14:21 +00006792 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006793 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6794 encoding, reason, unicode, &exc,
6795 collstart, collend, &newpos);
6796 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006797 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006798
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006799 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006800 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006801
Victor Stinner6bd525b2015-10-09 13:10:05 +02006802 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006803 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006804 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006805 PyBytes_AS_STRING(rep),
6806 PyBytes_GET_SIZE(rep));
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006807 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006808 else {
6809 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006810
Victor Stinner6bd525b2015-10-09 13:10:05 +02006811 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006812 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006813
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006814 if (limit == 256 ?
6815 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6816 !PyUnicode_IS_ASCII(rep))
6817 {
6818 /* Not all characters are smaller than limit */
6819 raise_encode_exception(&exc, encoding, unicode,
6820 collstart, collend, reason);
6821 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006822 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006823 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6824 str = _PyBytesWriter_WriteBytes(&writer, str,
6825 PyUnicode_DATA(rep),
6826 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006827 }
Alexey Izbyshev74a307d2018-08-19 21:52:04 +03006828 if (str == NULL)
6829 goto onError;
6830
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006831 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006832 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006833 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006834
6835 /* If overallocation was disabled, ensure that it was the last
6836 write. Otherwise, we missed an optimization */
6837 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006838 }
6839 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006840
Victor Stinner50149202015-09-22 00:26:54 +02006841 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006842 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006843 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006844
6845 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006846 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006847 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006848 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006849 Py_XDECREF(exc);
6850 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006851}
6852
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006853/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006854PyObject *
6855PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006856 Py_ssize_t size,
6857 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006858{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006859 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006860 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006861 if (unicode == NULL)
6862 return NULL;
6863 result = unicode_encode_ucs1(unicode, errors, 256);
6864 Py_DECREF(unicode);
6865 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006866}
6867
Alexander Belopolsky40018472011-02-26 01:02:56 +00006868PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006869_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006870{
6871 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006872 PyErr_BadArgument();
6873 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006874 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006875 if (PyUnicode_READY(unicode) == -1)
6876 return NULL;
6877 /* Fast path: if it is a one-byte string, construct
6878 bytes object directly. */
6879 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6880 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6881 PyUnicode_GET_LENGTH(unicode));
6882 /* Non-Latin-1 characters present. Defer to above function to
6883 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006884 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006885}
6886
6887PyObject*
6888PyUnicode_AsLatin1String(PyObject *unicode)
6889{
6890 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006891}
6892
6893/* --- 7-bit ASCII Codec -------------------------------------------------- */
6894
Alexander Belopolsky40018472011-02-26 01:02:56 +00006895PyObject *
6896PyUnicode_DecodeASCII(const char *s,
6897 Py_ssize_t size,
6898 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006899{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006900 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006901 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006902 int kind;
6903 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006904 Py_ssize_t startinpos;
6905 Py_ssize_t endinpos;
6906 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006907 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006908 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006909 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006910 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006911
Guido van Rossumd57fd912000-03-10 22:53:23 +00006912 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006913 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006914
Guido van Rossumd57fd912000-03-10 22:53:23 +00006915 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006916 if (size == 1 && (unsigned char)s[0] < 128)
6917 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006918
Victor Stinner8f674cc2013-04-17 23:02:17 +02006919 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006920 writer.min_length = size;
6921 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006922 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006923
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006924 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006925 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006926 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006927 writer.pos = outpos;
6928 if (writer.pos == size)
6929 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006930
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006931 s += writer.pos;
6932 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006933 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006934 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006935 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006936 PyUnicode_WRITE(kind, data, writer.pos, c);
6937 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006938 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006939 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006941
6942 /* byte outsize range 0x00..0x7f: call the error handler */
6943
6944 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006945 error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006946
6947 switch (error_handler)
6948 {
6949 case _Py_ERROR_REPLACE:
6950 case _Py_ERROR_SURROGATEESCAPE:
6951 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006952 but we may switch to UCS2 at the first write */
6953 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6954 goto onError;
6955 kind = writer.kind;
6956 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006957
6958 if (error_handler == _Py_ERROR_REPLACE)
6959 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6960 else
6961 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6962 writer.pos++;
6963 ++s;
6964 break;
6965
6966 case _Py_ERROR_IGNORE:
6967 ++s;
6968 break;
6969
6970 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006971 startinpos = s-starts;
6972 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006973 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006974 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006975 "ascii", "ordinal not in range(128)",
6976 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006977 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006979 kind = writer.kind;
6980 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006982 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006983 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006984 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006985 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006986
Benjamin Peterson29060642009-01-31 22:14:21 +00006987 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006988 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006989 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006990 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006991 return NULL;
6992}
6993
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006994/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006995PyObject *
6996PyUnicode_EncodeASCII(const Py_UNICODE *p,
6997 Py_ssize_t size,
6998 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006999{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007000 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007001 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007002 if (unicode == NULL)
7003 return NULL;
7004 result = unicode_encode_ucs1(unicode, errors, 128);
7005 Py_DECREF(unicode);
7006 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007007}
7008
Alexander Belopolsky40018472011-02-26 01:02:56 +00007009PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007010_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007011{
7012 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007013 PyErr_BadArgument();
7014 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007015 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007016 if (PyUnicode_READY(unicode) == -1)
7017 return NULL;
7018 /* Fast path: if it is an ASCII-only string, construct bytes object
7019 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007020 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007021 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7022 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007023 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007024}
7025
7026PyObject *
7027PyUnicode_AsASCIIString(PyObject *unicode)
7028{
7029 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007030}
7031
Steve Dowercc16be82016-09-08 10:35:16 -07007032#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007033
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007034/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007035
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007036#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007037#define NEED_RETRY
7038#endif
7039
Victor Stinner3a50e702011-10-18 21:21:00 +02007040#ifndef WC_ERR_INVALID_CHARS
7041# define WC_ERR_INVALID_CHARS 0x0080
7042#endif
7043
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007044static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007045code_page_name(UINT code_page, PyObject **obj)
7046{
7047 *obj = NULL;
7048 if (code_page == CP_ACP)
7049 return "mbcs";
7050 if (code_page == CP_UTF7)
7051 return "CP_UTF7";
7052 if (code_page == CP_UTF8)
7053 return "CP_UTF8";
7054
7055 *obj = PyBytes_FromFormat("cp%u", code_page);
7056 if (*obj == NULL)
7057 return NULL;
7058 return PyBytes_AS_STRING(*obj);
7059}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007060
Victor Stinner3a50e702011-10-18 21:21:00 +02007061static DWORD
7062decode_code_page_flags(UINT code_page)
7063{
7064 if (code_page == CP_UTF7) {
7065 /* The CP_UTF7 decoder only supports flags=0 */
7066 return 0;
7067 }
7068 else
7069 return MB_ERR_INVALID_CHARS;
7070}
7071
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007072/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007073 * Decode a byte string from a Windows code page into unicode object in strict
7074 * mode.
7075 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007076 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7077 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007078 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007079static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007080decode_code_page_strict(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007081 wchar_t **buf,
7082 Py_ssize_t *bufsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007083 const char *in,
7084 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007085{
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007086 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner24729f32011-11-10 20:31:37 +01007087 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007088 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007089
7090 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007091 assert(insize > 0);
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007092 while ((outsize = MultiByteToWideChar(code_page, flags,
7093 in, insize, NULL, 0)) <= 0)
7094 {
7095 if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
7096 goto error;
7097 }
7098 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7099 flags = 0;
7100 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007101
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007102 /* Extend a wchar_t* buffer */
7103 Py_ssize_t n = *bufsize; /* Get the current length */
7104 if (widechar_resize(buf, bufsize, n + outsize) < 0) {
7105 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007106 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007107 out = *buf + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007108
7109 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007110 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7111 if (outsize <= 0)
7112 goto error;
7113 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007114
Victor Stinner3a50e702011-10-18 21:21:00 +02007115error:
7116 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7117 return -2;
7118 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007119 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007120}
7121
Victor Stinner3a50e702011-10-18 21:21:00 +02007122/*
7123 * Decode a byte string from a code page into unicode object with an error
7124 * handler.
7125 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007126 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007127 * UnicodeDecodeError exception and returns -1 on error.
7128 */
7129static int
7130decode_code_page_errors(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007131 wchar_t **buf,
7132 Py_ssize_t *bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007133 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007134 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007135{
7136 const char *startin = in;
7137 const char *endin = in + size;
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007138 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007139 /* Ideally, we should get reason from FormatMessage. This is the Windows
7140 2000 English version of the message. */
7141 const char *reason = "No mapping for the Unicode character exists "
7142 "in the target code page.";
7143 /* each step cannot decode more than 1 character, but a character can be
7144 represented as a surrogate pair */
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007145 wchar_t buffer[2], *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007146 int insize;
7147 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007148 PyObject *errorHandler = NULL;
7149 PyObject *exc = NULL;
7150 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007151 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 DWORD err;
7153 int ret = -1;
7154
7155 assert(size > 0);
7156
7157 encoding = code_page_name(code_page, &encoding_obj);
7158 if (encoding == NULL)
7159 return -1;
7160
Victor Stinner7d00cc12014-03-17 23:08:06 +01007161 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007162 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7163 UnicodeDecodeError. */
7164 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7165 if (exc != NULL) {
7166 PyCodec_StrictErrors(exc);
7167 Py_CLEAR(exc);
7168 }
7169 goto error;
7170 }
7171
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007172 /* Extend a wchar_t* buffer */
7173 Py_ssize_t n = *bufsize; /* Get the current length */
7174 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7175 PyErr_NoMemory();
7176 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007177 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007178 if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
7179 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007181 out = *buf + n;
Victor Stinner3a50e702011-10-18 21:21:00 +02007182
7183 /* Decode the byte string character per character */
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 while (in < endin)
7185 {
7186 /* Decode a character */
7187 insize = 1;
7188 do
7189 {
7190 outsize = MultiByteToWideChar(code_page, flags,
7191 in, insize,
7192 buffer, Py_ARRAY_LENGTH(buffer));
7193 if (outsize > 0)
7194 break;
7195 err = GetLastError();
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007196 if (err == ERROR_INVALID_FLAGS && flags) {
7197 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7198 flags = 0;
7199 continue;
7200 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007201 if (err != ERROR_NO_UNICODE_TRANSLATION
7202 && err != ERROR_INSUFFICIENT_BUFFER)
7203 {
7204 PyErr_SetFromWindowsErr(0);
7205 goto error;
7206 }
7207 insize++;
7208 }
7209 /* 4=maximum length of a UTF-8 sequence */
7210 while (insize <= 4 && (in + insize) <= endin);
7211
7212 if (outsize <= 0) {
7213 Py_ssize_t startinpos, endinpos, outpos;
7214
Victor Stinner7d00cc12014-03-17 23:08:06 +01007215 /* last character in partial decode? */
7216 if (in + insize >= endin && !final)
7217 break;
7218
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 startinpos = in - startin;
7220 endinpos = startinpos + 1;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007221 outpos = out - *buf;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007222 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 errors, &errorHandler,
7224 encoding, reason,
7225 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007226 buf, bufsize, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 {
7228 goto error;
7229 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007230 out = *buf + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 }
7232 else {
7233 in += insize;
7234 memcpy(out, buffer, outsize * sizeof(wchar_t));
7235 out += outsize;
7236 }
7237 }
7238
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007239 /* Shrink the buffer */
7240 assert(out - *buf <= *bufsize);
7241 *bufsize = out - *buf;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007242 /* (in - startin) <= size and size is an int */
7243 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007244
7245error:
7246 Py_XDECREF(encoding_obj);
7247 Py_XDECREF(errorHandler);
7248 Py_XDECREF(exc);
7249 return ret;
7250}
7251
Victor Stinner3a50e702011-10-18 21:21:00 +02007252static PyObject *
7253decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007254 const char *s, Py_ssize_t size,
7255 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007256{
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007257 wchar_t *buf = NULL;
7258 Py_ssize_t bufsize = 0;
Victor Stinner76a31a62011-11-04 00:05:13 +01007259 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007260
Victor Stinner3a50e702011-10-18 21:21:00 +02007261 if (code_page < 0) {
7262 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7263 return NULL;
7264 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007265 if (size < 0) {
7266 PyErr_BadInternalCall();
7267 return NULL;
7268 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007269
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007270 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007271 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007272
Victor Stinner76a31a62011-11-04 00:05:13 +01007273 do
7274 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007275#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007276 if (size > INT_MAX) {
7277 chunk_size = INT_MAX;
7278 final = 0;
7279 done = 0;
7280 }
7281 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007283 {
7284 chunk_size = (int)size;
7285 final = (consumed == NULL);
7286 done = 1;
7287 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007288
Victor Stinner76a31a62011-11-04 00:05:13 +01007289 if (chunk_size == 0 && done) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007290 if (buf != NULL)
Victor Stinner76a31a62011-11-04 00:05:13 +01007291 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007292 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007293 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007294
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007295 converted = decode_code_page_strict(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007296 s, chunk_size);
7297 if (converted == -2)
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007298 converted = decode_code_page_errors(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007299 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007300 errors, final);
7301 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007302
7303 if (converted < 0) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007304 PyMem_Free(buf);
Victor Stinner76a31a62011-11-04 00:05:13 +01007305 return NULL;
7306 }
7307
7308 if (consumed)
7309 *consumed += converted;
7310
7311 s += converted;
7312 size -= converted;
7313 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007314
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007315 PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
7316 PyMem_Free(buf);
7317 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007318}
7319
Alexander Belopolsky40018472011-02-26 01:02:56 +00007320PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007321PyUnicode_DecodeCodePageStateful(int code_page,
7322 const char *s,
7323 Py_ssize_t size,
7324 const char *errors,
7325 Py_ssize_t *consumed)
7326{
7327 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7328}
7329
7330PyObject *
7331PyUnicode_DecodeMBCSStateful(const char *s,
7332 Py_ssize_t size,
7333 const char *errors,
7334 Py_ssize_t *consumed)
7335{
7336 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7337}
7338
7339PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007340PyUnicode_DecodeMBCS(const char *s,
7341 Py_ssize_t size,
7342 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007343{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007344 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7345}
7346
Victor Stinner3a50e702011-10-18 21:21:00 +02007347static DWORD
7348encode_code_page_flags(UINT code_page, const char *errors)
7349{
7350 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007351 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007352 }
7353 else if (code_page == CP_UTF7) {
7354 /* CP_UTF7 only supports flags=0 */
7355 return 0;
7356 }
7357 else {
7358 if (errors != NULL && strcmp(errors, "replace") == 0)
7359 return 0;
7360 else
7361 return WC_NO_BEST_FIT_CHARS;
7362 }
7363}
7364
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007366 * Encode a Unicode string to a Windows code page into a byte string in strict
7367 * mode.
7368 *
7369 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007370 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007371 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007372static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007373encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007374 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007376{
Victor Stinner554f3f02010-06-16 23:33:54 +00007377 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 BOOL *pusedDefaultChar = &usedDefaultChar;
7379 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007380 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007381 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007382 const DWORD flags = encode_code_page_flags(code_page, NULL);
7383 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007384 /* Create a substring so that we can get the UTF-16 representation
7385 of just the slice under consideration. */
7386 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007387
Martin v. Löwis3d325192011-11-04 18:23:06 +01007388 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007389
Victor Stinner3a50e702011-10-18 21:21:00 +02007390 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007391 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007392 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007393 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007394
Victor Stinner2fc507f2011-11-04 20:06:39 +01007395 substring = PyUnicode_Substring(unicode, offset, offset+len);
7396 if (substring == NULL)
7397 return -1;
7398 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7399 if (p == NULL) {
7400 Py_DECREF(substring);
7401 return -1;
7402 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007403 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007404
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007405 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007406 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007407 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007408 NULL, 0,
7409 NULL, pusedDefaultChar);
7410 if (outsize <= 0)
7411 goto error;
7412 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007413 if (pusedDefaultChar && *pusedDefaultChar) {
7414 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007415 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007416 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007417
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007419 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007421 if (*outbytes == NULL) {
7422 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007423 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007424 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007426 }
7427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007428 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007429 const Py_ssize_t n = PyBytes_Size(*outbytes);
7430 if (outsize > PY_SSIZE_T_MAX - n) {
7431 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007432 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007433 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007435 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7436 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007438 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007439 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007440 }
7441
7442 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007443 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007444 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 out, outsize,
7446 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007447 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 if (outsize <= 0)
7449 goto error;
7450 if (pusedDefaultChar && *pusedDefaultChar)
7451 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007452 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007453
Victor Stinner3a50e702011-10-18 21:21:00 +02007454error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7457 return -2;
7458 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007459 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007460}
7461
Victor Stinner3a50e702011-10-18 21:21:00 +02007462/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007463 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007464 * error handler.
7465 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007466 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 * -1 on other error.
7468 */
7469static int
7470encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007471 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007473{
Victor Stinner3a50e702011-10-18 21:21:00 +02007474 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007475 Py_ssize_t pos = unicode_offset;
7476 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007477 /* Ideally, we should get reason from FormatMessage. This is the Windows
7478 2000 English version of the message. */
7479 const char *reason = "invalid character";
7480 /* 4=maximum length of a UTF-8 sequence */
7481 char buffer[4];
7482 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7483 Py_ssize_t outsize;
7484 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007485 PyObject *errorHandler = NULL;
7486 PyObject *exc = NULL;
7487 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007488 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007489 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007490 PyObject *rep;
7491 int ret = -1;
7492
7493 assert(insize > 0);
7494
7495 encoding = code_page_name(code_page, &encoding_obj);
7496 if (encoding == NULL)
7497 return -1;
7498
7499 if (errors == NULL || strcmp(errors, "strict") == 0) {
7500 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7501 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007502 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007503 if (exc != NULL) {
7504 PyCodec_StrictErrors(exc);
7505 Py_DECREF(exc);
7506 }
7507 Py_XDECREF(encoding_obj);
7508 return -1;
7509 }
7510
7511 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7512 pusedDefaultChar = &usedDefaultChar;
7513 else
7514 pusedDefaultChar = NULL;
7515
7516 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7517 PyErr_NoMemory();
7518 goto error;
7519 }
7520 outsize = insize * Py_ARRAY_LENGTH(buffer);
7521
7522 if (*outbytes == NULL) {
7523 /* Create string object */
7524 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7525 if (*outbytes == NULL)
7526 goto error;
7527 out = PyBytes_AS_STRING(*outbytes);
7528 }
7529 else {
7530 /* Extend string object */
7531 Py_ssize_t n = PyBytes_Size(*outbytes);
7532 if (n > PY_SSIZE_T_MAX - outsize) {
7533 PyErr_NoMemory();
7534 goto error;
7535 }
7536 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7537 goto error;
7538 out = PyBytes_AS_STRING(*outbytes) + n;
7539 }
7540
7541 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007542 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007543 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007544 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7545 wchar_t chars[2];
7546 int charsize;
7547 if (ch < 0x10000) {
7548 chars[0] = (wchar_t)ch;
7549 charsize = 1;
7550 }
7551 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007552 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7553 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007554 charsize = 2;
7555 }
7556
Victor Stinner3a50e702011-10-18 21:21:00 +02007557 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007558 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007559 buffer, Py_ARRAY_LENGTH(buffer),
7560 NULL, pusedDefaultChar);
7561 if (outsize > 0) {
7562 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7563 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007564 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007565 memcpy(out, buffer, outsize);
7566 out += outsize;
7567 continue;
7568 }
7569 }
7570 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7571 PyErr_SetFromWindowsErr(0);
7572 goto error;
7573 }
7574
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 rep = unicode_encode_call_errorhandler(
7576 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007577 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007578 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007579 if (rep == NULL)
7580 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007581 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007582
7583 if (PyBytes_Check(rep)) {
7584 outsize = PyBytes_GET_SIZE(rep);
7585 if (outsize != 1) {
7586 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7587 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7588 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7589 Py_DECREF(rep);
7590 goto error;
7591 }
7592 out = PyBytes_AS_STRING(*outbytes) + offset;
7593 }
7594 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7595 out += outsize;
7596 }
7597 else {
7598 Py_ssize_t i;
7599 enum PyUnicode_Kind kind;
7600 void *data;
7601
Benjamin Petersonbac79492012-01-14 13:34:47 -05007602 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007603 Py_DECREF(rep);
7604 goto error;
7605 }
7606
7607 outsize = PyUnicode_GET_LENGTH(rep);
7608 if (outsize != 1) {
7609 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7610 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7611 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7612 Py_DECREF(rep);
7613 goto error;
7614 }
7615 out = PyBytes_AS_STRING(*outbytes) + offset;
7616 }
7617 kind = PyUnicode_KIND(rep);
7618 data = PyUnicode_DATA(rep);
7619 for (i=0; i < outsize; i++) {
7620 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7621 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007622 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007623 encoding, unicode,
7624 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007625 "unable to encode error handler result to ASCII");
7626 Py_DECREF(rep);
7627 goto error;
7628 }
7629 *out = (unsigned char)ch;
7630 out++;
7631 }
7632 }
7633 Py_DECREF(rep);
7634 }
7635 /* write a NUL byte */
7636 *out = 0;
7637 outsize = out - PyBytes_AS_STRING(*outbytes);
7638 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7639 if (_PyBytes_Resize(outbytes, outsize) < 0)
7640 goto error;
7641 ret = 0;
7642
7643error:
7644 Py_XDECREF(encoding_obj);
7645 Py_XDECREF(errorHandler);
7646 Py_XDECREF(exc);
7647 return ret;
7648}
7649
Victor Stinner3a50e702011-10-18 21:21:00 +02007650static PyObject *
7651encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007652 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007653 const char *errors)
7654{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007655 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007656 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007657 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007658 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007659
Victor Stinner29dacf22015-01-26 16:41:32 +01007660 if (!PyUnicode_Check(unicode)) {
7661 PyErr_BadArgument();
7662 return NULL;
7663 }
7664
Benjamin Petersonbac79492012-01-14 13:34:47 -05007665 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007666 return NULL;
7667 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007668
Victor Stinner3a50e702011-10-18 21:21:00 +02007669 if (code_page < 0) {
7670 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7671 return NULL;
7672 }
7673
Martin v. Löwis3d325192011-11-04 18:23:06 +01007674 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007675 return PyBytes_FromStringAndSize(NULL, 0);
7676
Victor Stinner7581cef2011-11-03 22:32:33 +01007677 offset = 0;
7678 do
7679 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007680#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007681 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007682 chunks. */
7683 if (len > INT_MAX/2) {
7684 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007685 done = 0;
7686 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007687 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007688#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007689 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007690 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007691 done = 1;
7692 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007693
Victor Stinner76a31a62011-11-04 00:05:13 +01007694 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007695 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007696 errors);
7697 if (ret == -2)
7698 ret = encode_code_page_errors(code_page, &outbytes,
7699 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007700 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007701 if (ret < 0) {
7702 Py_XDECREF(outbytes);
7703 return NULL;
7704 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007705
Victor Stinner7581cef2011-11-03 22:32:33 +01007706 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007707 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007708 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007709
Victor Stinner3a50e702011-10-18 21:21:00 +02007710 return outbytes;
7711}
7712
7713PyObject *
7714PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7715 Py_ssize_t size,
7716 const char *errors)
7717{
Victor Stinner7581cef2011-11-03 22:32:33 +01007718 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007719 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007720 if (unicode == NULL)
7721 return NULL;
7722 res = encode_code_page(CP_ACP, unicode, errors);
7723 Py_DECREF(unicode);
7724 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007725}
7726
7727PyObject *
7728PyUnicode_EncodeCodePage(int code_page,
7729 PyObject *unicode,
7730 const char *errors)
7731{
Victor Stinner7581cef2011-11-03 22:32:33 +01007732 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007733}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007734
Alexander Belopolsky40018472011-02-26 01:02:56 +00007735PyObject *
7736PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007737{
Victor Stinner7581cef2011-11-03 22:32:33 +01007738 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007739}
7740
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007741#undef NEED_RETRY
7742
Steve Dowercc16be82016-09-08 10:35:16 -07007743#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007744
Guido van Rossumd57fd912000-03-10 22:53:23 +00007745/* --- Character Mapping Codec -------------------------------------------- */
7746
Victor Stinnerfb161b12013-04-18 01:44:27 +02007747static int
7748charmap_decode_string(const char *s,
7749 Py_ssize_t size,
7750 PyObject *mapping,
7751 const char *errors,
7752 _PyUnicodeWriter *writer)
7753{
7754 const char *starts = s;
7755 const char *e;
7756 Py_ssize_t startinpos, endinpos;
7757 PyObject *errorHandler = NULL, *exc = NULL;
7758 Py_ssize_t maplen;
7759 enum PyUnicode_Kind mapkind;
7760 void *mapdata;
7761 Py_UCS4 x;
7762 unsigned char ch;
7763
7764 if (PyUnicode_READY(mapping) == -1)
7765 return -1;
7766
7767 maplen = PyUnicode_GET_LENGTH(mapping);
7768 mapdata = PyUnicode_DATA(mapping);
7769 mapkind = PyUnicode_KIND(mapping);
7770
7771 e = s + size;
7772
7773 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7774 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7775 * is disabled in encoding aliases, latin1 is preferred because
7776 * its implementation is faster. */
7777 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7778 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7779 Py_UCS4 maxchar = writer->maxchar;
7780
7781 assert (writer->kind == PyUnicode_1BYTE_KIND);
7782 while (s < e) {
7783 ch = *s;
7784 x = mapdata_ucs1[ch];
7785 if (x > maxchar) {
7786 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7787 goto onError;
7788 maxchar = writer->maxchar;
7789 outdata = (Py_UCS1 *)writer->data;
7790 }
7791 outdata[writer->pos] = x;
7792 writer->pos++;
7793 ++s;
7794 }
7795 return 0;
7796 }
7797
7798 while (s < e) {
7799 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7800 enum PyUnicode_Kind outkind = writer->kind;
7801 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7802 if (outkind == PyUnicode_1BYTE_KIND) {
7803 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7804 Py_UCS4 maxchar = writer->maxchar;
7805 while (s < e) {
7806 ch = *s;
7807 x = mapdata_ucs2[ch];
7808 if (x > maxchar)
7809 goto Error;
7810 outdata[writer->pos] = x;
7811 writer->pos++;
7812 ++s;
7813 }
7814 break;
7815 }
7816 else if (outkind == PyUnicode_2BYTE_KIND) {
7817 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7818 while (s < e) {
7819 ch = *s;
7820 x = mapdata_ucs2[ch];
7821 if (x == 0xFFFE)
7822 goto Error;
7823 outdata[writer->pos] = x;
7824 writer->pos++;
7825 ++s;
7826 }
7827 break;
7828 }
7829 }
7830 ch = *s;
7831
7832 if (ch < maplen)
7833 x = PyUnicode_READ(mapkind, mapdata, ch);
7834 else
7835 x = 0xfffe; /* invalid value */
7836Error:
7837 if (x == 0xfffe)
7838 {
7839 /* undefined mapping */
7840 startinpos = s-starts;
7841 endinpos = startinpos+1;
7842 if (unicode_decode_call_errorhandler_writer(
7843 errors, &errorHandler,
7844 "charmap", "character maps to <undefined>",
7845 &starts, &e, &startinpos, &endinpos, &exc, &s,
7846 writer)) {
7847 goto onError;
7848 }
7849 continue;
7850 }
7851
7852 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7853 goto onError;
7854 ++s;
7855 }
7856 Py_XDECREF(errorHandler);
7857 Py_XDECREF(exc);
7858 return 0;
7859
7860onError:
7861 Py_XDECREF(errorHandler);
7862 Py_XDECREF(exc);
7863 return -1;
7864}
7865
7866static int
7867charmap_decode_mapping(const char *s,
7868 Py_ssize_t size,
7869 PyObject *mapping,
7870 const char *errors,
7871 _PyUnicodeWriter *writer)
7872{
7873 const char *starts = s;
7874 const char *e;
7875 Py_ssize_t startinpos, endinpos;
7876 PyObject *errorHandler = NULL, *exc = NULL;
7877 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007878 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007879
7880 e = s + size;
7881
7882 while (s < e) {
7883 ch = *s;
7884
7885 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7886 key = PyLong_FromLong((long)ch);
7887 if (key == NULL)
7888 goto onError;
7889
7890 item = PyObject_GetItem(mapping, key);
7891 Py_DECREF(key);
7892 if (item == NULL) {
7893 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7894 /* No mapping found means: mapping is undefined. */
7895 PyErr_Clear();
7896 goto Undefined;
7897 } else
7898 goto onError;
7899 }
7900
7901 /* Apply mapping */
7902 if (item == Py_None)
7903 goto Undefined;
7904 if (PyLong_Check(item)) {
7905 long value = PyLong_AS_LONG(item);
7906 if (value == 0xFFFE)
7907 goto Undefined;
7908 if (value < 0 || value > MAX_UNICODE) {
7909 PyErr_Format(PyExc_TypeError,
7910 "character mapping must be in range(0x%lx)",
7911 (unsigned long)MAX_UNICODE + 1);
7912 goto onError;
7913 }
7914
7915 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7916 goto onError;
7917 }
7918 else if (PyUnicode_Check(item)) {
7919 if (PyUnicode_READY(item) == -1)
7920 goto onError;
7921 if (PyUnicode_GET_LENGTH(item) == 1) {
7922 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7923 if (value == 0xFFFE)
7924 goto Undefined;
7925 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7926 goto onError;
7927 }
7928 else {
7929 writer->overallocate = 1;
7930 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7931 goto onError;
7932 }
7933 }
7934 else {
7935 /* wrong return value */
7936 PyErr_SetString(PyExc_TypeError,
7937 "character mapping must return integer, None or str");
7938 goto onError;
7939 }
7940 Py_CLEAR(item);
7941 ++s;
7942 continue;
7943
7944Undefined:
7945 /* undefined mapping */
7946 Py_CLEAR(item);
7947 startinpos = s-starts;
7948 endinpos = startinpos+1;
7949 if (unicode_decode_call_errorhandler_writer(
7950 errors, &errorHandler,
7951 "charmap", "character maps to <undefined>",
7952 &starts, &e, &startinpos, &endinpos, &exc, &s,
7953 writer)) {
7954 goto onError;
7955 }
7956 }
7957 Py_XDECREF(errorHandler);
7958 Py_XDECREF(exc);
7959 return 0;
7960
7961onError:
7962 Py_XDECREF(item);
7963 Py_XDECREF(errorHandler);
7964 Py_XDECREF(exc);
7965 return -1;
7966}
7967
Alexander Belopolsky40018472011-02-26 01:02:56 +00007968PyObject *
7969PyUnicode_DecodeCharmap(const char *s,
7970 Py_ssize_t size,
7971 PyObject *mapping,
7972 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007973{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007974 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007975
Guido van Rossumd57fd912000-03-10 22:53:23 +00007976 /* Default to Latin-1 */
7977 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007978 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007979
Guido van Rossumd57fd912000-03-10 22:53:23 +00007980 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007981 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007982 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007983 writer.min_length = size;
7984 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007985 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007986
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007987 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007988 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7989 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007990 }
7991 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007992 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7993 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007994 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007995 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007996
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007998 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007999 return NULL;
8000}
8001
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008002/* Charmap encoding: the lookup table */
8003
Alexander Belopolsky40018472011-02-26 01:02:56 +00008004struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 PyObject_HEAD
8006 unsigned char level1[32];
8007 int count2, count3;
8008 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008009};
8010
8011static PyObject*
8012encoding_map_size(PyObject *obj, PyObject* args)
8013{
8014 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008015 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008016 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008017}
8018
8019static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008020 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 PyDoc_STR("Return the size (in bytes) of this object") },
8022 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008023};
8024
8025static void
8026encoding_map_dealloc(PyObject* o)
8027{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008028 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029}
8030
8031static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008032 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008033 "EncodingMap", /*tp_name*/
8034 sizeof(struct encoding_map), /*tp_basicsize*/
8035 0, /*tp_itemsize*/
8036 /* methods */
8037 encoding_map_dealloc, /*tp_dealloc*/
8038 0, /*tp_print*/
8039 0, /*tp_getattr*/
8040 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008041 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008042 0, /*tp_repr*/
8043 0, /*tp_as_number*/
8044 0, /*tp_as_sequence*/
8045 0, /*tp_as_mapping*/
8046 0, /*tp_hash*/
8047 0, /*tp_call*/
8048 0, /*tp_str*/
8049 0, /*tp_getattro*/
8050 0, /*tp_setattro*/
8051 0, /*tp_as_buffer*/
8052 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8053 0, /*tp_doc*/
8054 0, /*tp_traverse*/
8055 0, /*tp_clear*/
8056 0, /*tp_richcompare*/
8057 0, /*tp_weaklistoffset*/
8058 0, /*tp_iter*/
8059 0, /*tp_iternext*/
8060 encoding_map_methods, /*tp_methods*/
8061 0, /*tp_members*/
8062 0, /*tp_getset*/
8063 0, /*tp_base*/
8064 0, /*tp_dict*/
8065 0, /*tp_descr_get*/
8066 0, /*tp_descr_set*/
8067 0, /*tp_dictoffset*/
8068 0, /*tp_init*/
8069 0, /*tp_alloc*/
8070 0, /*tp_new*/
8071 0, /*tp_free*/
8072 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008073};
8074
8075PyObject*
8076PyUnicode_BuildEncodingMap(PyObject* string)
8077{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008078 PyObject *result;
8079 struct encoding_map *mresult;
8080 int i;
8081 int need_dict = 0;
8082 unsigned char level1[32];
8083 unsigned char level2[512];
8084 unsigned char *mlevel1, *mlevel2, *mlevel3;
8085 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008086 int kind;
8087 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008088 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008089 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008091 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008092 PyErr_BadArgument();
8093 return NULL;
8094 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008095 kind = PyUnicode_KIND(string);
8096 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008097 length = PyUnicode_GET_LENGTH(string);
8098 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008099 memset(level1, 0xFF, sizeof level1);
8100 memset(level2, 0xFF, sizeof level2);
8101
8102 /* If there isn't a one-to-one mapping of NULL to \0,
8103 or if there are non-BMP characters, we need to use
8104 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008105 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008107 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008109 ch = PyUnicode_READ(kind, data, i);
8110 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111 need_dict = 1;
8112 break;
8113 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008114 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008115 /* unmapped character */
8116 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008117 l1 = ch >> 11;
8118 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008119 if (level1[l1] == 0xFF)
8120 level1[l1] = count2++;
8121 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008122 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 }
8124
8125 if (count2 >= 0xFF || count3 >= 0xFF)
8126 need_dict = 1;
8127
8128 if (need_dict) {
8129 PyObject *result = PyDict_New();
8130 PyObject *key, *value;
8131 if (!result)
8132 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008133 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008134 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008135 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 if (!key || !value)
8137 goto failed1;
8138 if (PyDict_SetItem(result, key, value) == -1)
8139 goto failed1;
8140 Py_DECREF(key);
8141 Py_DECREF(value);
8142 }
8143 return result;
8144 failed1:
8145 Py_XDECREF(key);
8146 Py_XDECREF(value);
8147 Py_DECREF(result);
8148 return NULL;
8149 }
8150
8151 /* Create a three-level trie */
8152 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8153 16*count2 + 128*count3 - 1);
8154 if (!result)
8155 return PyErr_NoMemory();
8156 PyObject_Init(result, &EncodingMapType);
8157 mresult = (struct encoding_map*)result;
8158 mresult->count2 = count2;
8159 mresult->count3 = count3;
8160 mlevel1 = mresult->level1;
8161 mlevel2 = mresult->level23;
8162 mlevel3 = mresult->level23 + 16*count2;
8163 memcpy(mlevel1, level1, 32);
8164 memset(mlevel2, 0xFF, 16*count2);
8165 memset(mlevel3, 0, 128*count3);
8166 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008167 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008168 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008169 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8170 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171 /* unmapped character */
8172 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008173 o1 = ch>>11;
8174 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008175 i2 = 16*mlevel1[o1] + o2;
8176 if (mlevel2[i2] == 0xFF)
8177 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008178 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008179 i3 = 128*mlevel2[i2] + o3;
8180 mlevel3[i3] = i;
8181 }
8182 return result;
8183}
8184
8185static int
Victor Stinner22168992011-11-20 17:09:18 +01008186encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187{
8188 struct encoding_map *map = (struct encoding_map*)mapping;
8189 int l1 = c>>11;
8190 int l2 = (c>>7) & 0xF;
8191 int l3 = c & 0x7F;
8192 int i;
8193
Victor Stinner22168992011-11-20 17:09:18 +01008194 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008195 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008196 if (c == 0)
8197 return 0;
8198 /* level 1*/
8199 i = map->level1[l1];
8200 if (i == 0xFF) {
8201 return -1;
8202 }
8203 /* level 2*/
8204 i = map->level23[16*i+l2];
8205 if (i == 0xFF) {
8206 return -1;
8207 }
8208 /* level 3 */
8209 i = map->level23[16*map->count2 + 128*i + l3];
8210 if (i == 0) {
8211 return -1;
8212 }
8213 return i;
8214}
8215
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216/* Lookup the character ch in the mapping. If the character
8217 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008218 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008219static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008220charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008221{
Christian Heimes217cfd12007-12-02 14:31:20 +00008222 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 PyObject *x;
8224
8225 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008227 x = PyObject_GetItem(mapping, w);
8228 Py_DECREF(w);
8229 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8231 /* No mapping found means: mapping is undefined. */
8232 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008233 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 } else
8235 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008236 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008237 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008238 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008239 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 long value = PyLong_AS_LONG(x);
8241 if (value < 0 || value > 255) {
8242 PyErr_SetString(PyExc_TypeError,
8243 "character mapping must be in range(256)");
8244 Py_DECREF(x);
8245 return NULL;
8246 }
8247 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008248 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008249 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 /* wrong return value */
8253 PyErr_Format(PyExc_TypeError,
8254 "character mapping must return integer, bytes or None, not %.400s",
8255 x->ob_type->tp_name);
8256 Py_DECREF(x);
8257 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008258 }
8259}
8260
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008261static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008262charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008263{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008264 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8265 /* exponentially overallocate to minimize reallocations */
8266 if (requiredsize < 2*outsize)
8267 requiredsize = 2*outsize;
8268 if (_PyBytes_Resize(outobj, requiredsize))
8269 return -1;
8270 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008271}
8272
Benjamin Peterson14339b62009-01-31 16:36:08 +00008273typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008275} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008277 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008278 space is available. Return a new reference to the object that
8279 was put in the output buffer, or Py_None, if the mapping was undefined
8280 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008281 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008282static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008283charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008284 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008285{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008286 PyObject *rep;
8287 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008288 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289
Christian Heimes90aa7642007-12-19 02:45:37 +00008290 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008291 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008293 if (res == -1)
8294 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008295 if (outsize<requiredsize)
8296 if (charmapencode_resize(outobj, outpos, requiredsize))
8297 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008298 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 outstart[(*outpos)++] = (char)res;
8300 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008301 }
8302
8303 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008304 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008306 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 Py_DECREF(rep);
8308 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008309 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 if (PyLong_Check(rep)) {
8311 Py_ssize_t requiredsize = *outpos+1;
8312 if (outsize<requiredsize)
8313 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8314 Py_DECREF(rep);
8315 return enc_EXCEPTION;
8316 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008317 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008319 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 else {
8321 const char *repchars = PyBytes_AS_STRING(rep);
8322 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8323 Py_ssize_t requiredsize = *outpos+repsize;
8324 if (outsize<requiredsize)
8325 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8326 Py_DECREF(rep);
8327 return enc_EXCEPTION;
8328 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008329 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 memcpy(outstart + *outpos, repchars, repsize);
8331 *outpos += repsize;
8332 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008334 Py_DECREF(rep);
8335 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008336}
8337
8338/* handle an error in PyUnicode_EncodeCharmap
8339 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008340static int
8341charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008342 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008343 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008344 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008345 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346{
8347 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008348 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008349 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008350 enum PyUnicode_Kind kind;
8351 void *data;
8352 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008354 Py_ssize_t collstartpos = *inpos;
8355 Py_ssize_t collendpos = *inpos+1;
8356 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008357 const char *encoding = "charmap";
8358 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008359 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008360 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008361 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362
Benjamin Petersonbac79492012-01-14 13:34:47 -05008363 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008364 return -1;
8365 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366 /* find all unencodable characters */
8367 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008368 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008369 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008370 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008371 val = encoding_map_lookup(ch, mapping);
8372 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008373 break;
8374 ++collendpos;
8375 continue;
8376 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008377
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008378 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8379 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 if (rep==NULL)
8381 return -1;
8382 else if (rep!=Py_None) {
8383 Py_DECREF(rep);
8384 break;
8385 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008386 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008388 }
8389 /* cache callback name lookup
8390 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008391 if (*error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02008392 *error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02008393
8394 switch (*error_handler) {
8395 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008396 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008397 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008398
8399 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008400 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 x = charmapencode_output('?', mapping, res, respos);
8402 if (x==enc_EXCEPTION) {
8403 return -1;
8404 }
8405 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008406 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 return -1;
8408 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008409 }
8410 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008411 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008412 *inpos = collendpos;
8413 break;
Victor Stinner50149202015-09-22 00:26:54 +02008414
8415 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008416 /* generate replacement (temporarily (mis)uses p) */
8417 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 char buffer[2+29+1+1];
8419 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008420 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 for (cp = buffer; *cp; ++cp) {
8422 x = charmapencode_output(*cp, mapping, res, respos);
8423 if (x==enc_EXCEPTION)
8424 return -1;
8425 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008426 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 return -1;
8428 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008429 }
8430 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008431 *inpos = collendpos;
8432 break;
Victor Stinner50149202015-09-22 00:26:54 +02008433
Benjamin Peterson14339b62009-01-31 16:36:08 +00008434 default:
Victor Stinner50149202015-09-22 00:26:54 +02008435 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008436 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008438 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008439 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008440 if (PyBytes_Check(repunicode)) {
8441 /* Directly copy bytes result to output. */
8442 Py_ssize_t outsize = PyBytes_Size(*res);
8443 Py_ssize_t requiredsize;
8444 repsize = PyBytes_Size(repunicode);
8445 requiredsize = *respos + repsize;
8446 if (requiredsize > outsize)
8447 /* Make room for all additional bytes. */
8448 if (charmapencode_resize(res, respos, requiredsize)) {
8449 Py_DECREF(repunicode);
8450 return -1;
8451 }
8452 memcpy(PyBytes_AsString(*res) + *respos,
8453 PyBytes_AsString(repunicode), repsize);
8454 *respos += repsize;
8455 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008456 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008457 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008458 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008459 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008460 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008461 Py_DECREF(repunicode);
8462 return -1;
8463 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008464 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008465 data = PyUnicode_DATA(repunicode);
8466 kind = PyUnicode_KIND(repunicode);
8467 for (index = 0; index < repsize; index++) {
8468 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8469 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008471 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 return -1;
8473 }
8474 else if (x==enc_FAILED) {
8475 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008476 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 return -1;
8478 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008479 }
8480 *inpos = newpos;
8481 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482 }
8483 return 0;
8484}
8485
Alexander Belopolsky40018472011-02-26 01:02:56 +00008486PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008487_PyUnicode_EncodeCharmap(PyObject *unicode,
8488 PyObject *mapping,
8489 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008490{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008491 /* output object */
8492 PyObject *res = NULL;
8493 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008494 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008495 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008497 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008498 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008499 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008500 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008501 void *data;
8502 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008503
Benjamin Petersonbac79492012-01-14 13:34:47 -05008504 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008505 return NULL;
8506 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008507 data = PyUnicode_DATA(unicode);
8508 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008509
Guido van Rossumd57fd912000-03-10 22:53:23 +00008510 /* Default to Latin-1 */
8511 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008512 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008513
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008514 /* allocate enough for a simple encoding without
8515 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008516 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008517 if (res == NULL)
8518 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008519 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008521
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008523 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008525 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008526 if (x==enc_EXCEPTION) /* error */
8527 goto onError;
8528 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008529 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008531 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 &res, &respos)) {
8533 goto onError;
8534 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008535 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008536 else
8537 /* done with this character => adjust input position */
8538 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008539 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008540
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008542 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008543 if (_PyBytes_Resize(&res, respos) < 0)
8544 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008545
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008546 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008547 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008548 return res;
8549
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551 Py_XDECREF(res);
8552 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008553 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008554 return NULL;
8555}
8556
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008557/* Deprecated */
8558PyObject *
8559PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8560 Py_ssize_t size,
8561 PyObject *mapping,
8562 const char *errors)
8563{
8564 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008565 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008566 if (unicode == NULL)
8567 return NULL;
8568 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8569 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008570 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008571}
8572
Alexander Belopolsky40018472011-02-26 01:02:56 +00008573PyObject *
8574PyUnicode_AsCharmapString(PyObject *unicode,
8575 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008576{
8577 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008578 PyErr_BadArgument();
8579 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008580 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008581 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008582}
8583
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008584/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008585static void
8586make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008588 Py_ssize_t startpos, Py_ssize_t endpos,
8589 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008592 *exceptionObject = _PyUnicodeTranslateError_Create(
8593 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594 }
8595 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008596 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8597 goto onError;
8598 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8599 goto onError;
8600 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8601 goto onError;
8602 return;
8603 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008604 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008605 }
8606}
8607
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608/* error handling callback helper:
8609 build arguments, call the callback and check the arguments,
8610 put the result into newpos and return the replacement string, which
8611 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008612static PyObject *
8613unicode_translate_call_errorhandler(const char *errors,
8614 PyObject **errorHandler,
8615 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008617 Py_ssize_t startpos, Py_ssize_t endpos,
8618 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008619{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008620 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008621
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008622 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623 PyObject *restuple;
8624 PyObject *resunicode;
8625
8626 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008630 }
8631
8632 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008635 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008636
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008637 restuple = PyObject_CallFunctionObjArgs(
8638 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008642 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 Py_DECREF(restuple);
8644 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008645 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008646 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 &resunicode, &i_newpos)) {
8648 Py_DECREF(restuple);
8649 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008651 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008653 else
8654 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008656 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 Py_DECREF(restuple);
8658 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008659 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008660 Py_INCREF(resunicode);
8661 Py_DECREF(restuple);
8662 return resunicode;
8663}
8664
8665/* Lookup the character ch in the mapping and put the result in result,
8666 which must be decrefed by the caller.
8667 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008668static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008669charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008670{
Christian Heimes217cfd12007-12-02 14:31:20 +00008671 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008672 PyObject *x;
8673
8674 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008676 x = PyObject_GetItem(mapping, w);
8677 Py_DECREF(w);
8678 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008679 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8680 /* No mapping found means: use 1:1 mapping. */
8681 PyErr_Clear();
8682 *result = NULL;
8683 return 0;
8684 } else
8685 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008686 }
8687 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008688 *result = x;
8689 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008690 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008691 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008693 if (value < 0 || value > MAX_UNICODE) {
8694 PyErr_Format(PyExc_ValueError,
8695 "character mapping must be in range(0x%x)",
8696 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 Py_DECREF(x);
8698 return -1;
8699 }
8700 *result = x;
8701 return 0;
8702 }
8703 else if (PyUnicode_Check(x)) {
8704 *result = x;
8705 return 0;
8706 }
8707 else {
8708 /* wrong return value */
8709 PyErr_SetString(PyExc_TypeError,
8710 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008711 Py_DECREF(x);
8712 return -1;
8713 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008714}
Victor Stinner1194ea02014-04-04 19:37:40 +02008715
8716/* lookup the character, write the result into the writer.
8717 Return 1 if the result was written into the writer, return 0 if the mapping
8718 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008719static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008720charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8721 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008722{
Victor Stinner1194ea02014-04-04 19:37:40 +02008723 PyObject *item;
8724
8725 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008727
8728 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008730 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008733 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008734 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008735
8736 if (item == Py_None) {
8737 Py_DECREF(item);
8738 return 0;
8739 }
8740
8741 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008742 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8743 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8744 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008745 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8746 Py_DECREF(item);
8747 return -1;
8748 }
8749 Py_DECREF(item);
8750 return 1;
8751 }
8752
8753 if (!PyUnicode_Check(item)) {
8754 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008756 }
8757
8758 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8759 Py_DECREF(item);
8760 return -1;
8761 }
8762
8763 Py_DECREF(item);
8764 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008765}
8766
Victor Stinner89a76ab2014-04-05 11:44:04 +02008767static int
8768unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8769 Py_UCS1 *translate)
8770{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008771 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008772 int ret = 0;
8773
Victor Stinner89a76ab2014-04-05 11:44:04 +02008774 if (charmaptranslate_lookup(ch, mapping, &item)) {
8775 return -1;
8776 }
8777
8778 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008779 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008780 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008781 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008782 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008783 /* not found => default to 1:1 mapping */
8784 translate[ch] = ch;
8785 return 1;
8786 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008787 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008788 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008789 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8790 used it */
8791 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008792 /* invalid character or character outside ASCII:
8793 skip the fast translate */
8794 goto exit;
8795 }
8796 translate[ch] = (Py_UCS1)replace;
8797 }
8798 else if (PyUnicode_Check(item)) {
8799 Py_UCS4 replace;
8800
8801 if (PyUnicode_READY(item) == -1) {
8802 Py_DECREF(item);
8803 return -1;
8804 }
8805 if (PyUnicode_GET_LENGTH(item) != 1)
8806 goto exit;
8807
8808 replace = PyUnicode_READ_CHAR(item, 0);
8809 if (replace > 127)
8810 goto exit;
8811 translate[ch] = (Py_UCS1)replace;
8812 }
8813 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008814 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008815 goto exit;
8816 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008817 ret = 1;
8818
Benjamin Peterson1365de72014-04-07 20:15:41 -04008819 exit:
8820 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008821 return ret;
8822}
8823
8824/* Fast path for ascii => ascii translation. Return 1 if the whole string
8825 was translated into writer, return 0 if the input string was partially
8826 translated into writer, raise an exception and return -1 on error. */
8827static int
8828unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008829 _PyUnicodeWriter *writer, int ignore,
8830 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008831{
Victor Stinner872b2912014-04-05 14:27:07 +02008832 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008833 Py_ssize_t len;
8834 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008835 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008836
Victor Stinner89a76ab2014-04-05 11:44:04 +02008837 len = PyUnicode_GET_LENGTH(input);
8838
Victor Stinner872b2912014-04-05 14:27:07 +02008839 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008840
8841 in = PyUnicode_1BYTE_DATA(input);
8842 end = in + len;
8843
8844 assert(PyUnicode_IS_ASCII(writer->buffer));
8845 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8846 out = PyUnicode_1BYTE_DATA(writer->buffer);
8847
Victor Stinner872b2912014-04-05 14:27:07 +02008848 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008849 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008850 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008851 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008852 int translate = unicode_fast_translate_lookup(mapping, ch,
8853 ascii_table);
8854 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008855 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008856 if (translate == 0)
8857 goto exit;
8858 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008859 }
Victor Stinner872b2912014-04-05 14:27:07 +02008860 if (ch2 == 0xfe) {
8861 if (ignore)
8862 continue;
8863 goto exit;
8864 }
8865 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008866 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008867 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008868 }
Victor Stinner872b2912014-04-05 14:27:07 +02008869 res = 1;
8870
8871exit:
8872 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008873 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008874 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008875}
8876
Victor Stinner3222da22015-10-01 22:07:32 +02008877static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008878_PyUnicode_TranslateCharmap(PyObject *input,
8879 PyObject *mapping,
8880 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008881{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008882 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008883 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884 Py_ssize_t size, i;
8885 int kind;
8886 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008887 _PyUnicodeWriter writer;
8888 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008889 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008890 PyObject *errorHandler = NULL;
8891 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008892 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008893 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008894
Guido van Rossumd57fd912000-03-10 22:53:23 +00008895 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008896 PyErr_BadArgument();
8897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008898 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008900 if (PyUnicode_READY(input) == -1)
8901 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008902 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008903 kind = PyUnicode_KIND(input);
8904 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008905
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008906 if (size == 0)
8907 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008908
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008909 /* allocate enough for a simple 1:1 translation without
8910 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008911 _PyUnicodeWriter_Init(&writer);
8912 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008913 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008914
Victor Stinner872b2912014-04-05 14:27:07 +02008915 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8916
Victor Stinner33798672016-03-01 21:59:58 +01008917 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008918 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008919 if (PyUnicode_IS_ASCII(input)) {
8920 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8921 if (res < 0) {
8922 _PyUnicodeWriter_Dealloc(&writer);
8923 return NULL;
8924 }
8925 if (res == 1)
8926 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008927 }
Victor Stinner33798672016-03-01 21:59:58 +01008928 else {
8929 i = 0;
8930 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008931
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008932 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008933 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008934 int translate;
8935 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8936 Py_ssize_t newpos;
8937 /* startpos for collecting untranslatable chars */
8938 Py_ssize_t collstart;
8939 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008940 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008941
Victor Stinner1194ea02014-04-04 19:37:40 +02008942 ch = PyUnicode_READ(kind, data, i);
8943 translate = charmaptranslate_output(ch, mapping, &writer);
8944 if (translate < 0)
8945 goto onError;
8946
8947 if (translate != 0) {
8948 /* it worked => adjust input pointer */
8949 ++i;
8950 continue;
8951 }
8952
8953 /* untranslatable character */
8954 collstart = i;
8955 collend = i+1;
8956
8957 /* find all untranslatable characters */
8958 while (collend < size) {
8959 PyObject *x;
8960 ch = PyUnicode_READ(kind, data, collend);
8961 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008962 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008963 Py_XDECREF(x);
8964 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008965 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008966 ++collend;
8967 }
8968
8969 if (ignore) {
8970 i = collend;
8971 }
8972 else {
8973 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8974 reason, input, &exc,
8975 collstart, collend, &newpos);
8976 if (repunicode == NULL)
8977 goto onError;
8978 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008979 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008980 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008981 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008982 Py_DECREF(repunicode);
8983 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008984 }
8985 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008986 Py_XDECREF(exc);
8987 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008988 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008989
Benjamin Peterson29060642009-01-31 22:14:21 +00008990 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008991 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008992 Py_XDECREF(exc);
8993 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008994 return NULL;
8995}
8996
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008997/* Deprecated. Use PyUnicode_Translate instead. */
8998PyObject *
8999PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9000 Py_ssize_t size,
9001 PyObject *mapping,
9002 const char *errors)
9003{
Christian Heimes5f520f42012-09-11 14:03:25 +02009004 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009005 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009006 if (!unicode)
9007 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009008 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9009 Py_DECREF(unicode);
9010 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011}
9012
Alexander Belopolsky40018472011-02-26 01:02:56 +00009013PyObject *
9014PyUnicode_Translate(PyObject *str,
9015 PyObject *mapping,
9016 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009017{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009018 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009019 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009020 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021}
Tim Petersced69f82003-09-16 20:30:58 +00009022
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009023PyObject *
9024_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9025{
9026 if (!PyUnicode_Check(unicode)) {
9027 PyErr_BadInternalCall();
9028 return NULL;
9029 }
9030 if (PyUnicode_READY(unicode) == -1)
9031 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009032 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009033 /* If the string is already ASCII, just return the same string */
9034 Py_INCREF(unicode);
9035 return unicode;
9036 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009037
9038 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9039 PyObject *result = PyUnicode_New(len, 127);
9040 if (result == NULL) {
9041 return NULL;
9042 }
9043
9044 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9045 int kind = PyUnicode_KIND(unicode);
9046 const void *data = PyUnicode_DATA(unicode);
9047 Py_ssize_t i;
9048 for (i = 0; i < len; ++i) {
9049 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9050 if (ch < 127) {
9051 out[i] = ch;
9052 }
9053 else if (Py_UNICODE_ISSPACE(ch)) {
9054 out[i] = ' ';
9055 }
9056 else {
9057 int decimal = Py_UNICODE_TODECIMAL(ch);
9058 if (decimal < 0) {
9059 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009060 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009061 _PyUnicode_LENGTH(result) = i + 1;
9062 break;
9063 }
9064 out[i] = '0' + decimal;
9065 }
9066 }
9067
INADA Naoki16dfca42018-07-14 12:06:43 +09009068 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009069 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009070}
9071
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009072PyObject *
9073PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9074 Py_ssize_t length)
9075{
Victor Stinnerf0124502011-11-21 23:12:56 +01009076 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009077 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009078 Py_UCS4 maxchar;
9079 enum PyUnicode_Kind kind;
9080 void *data;
9081
Victor Stinner99d7ad02012-02-22 13:37:39 +01009082 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009083 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009084 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009085 if (ch > 127) {
9086 int decimal = Py_UNICODE_TODECIMAL(ch);
9087 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009088 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009089 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009090 }
9091 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009092
9093 /* Copy to a new string */
9094 decimal = PyUnicode_New(length, maxchar);
9095 if (decimal == NULL)
9096 return decimal;
9097 kind = PyUnicode_KIND(decimal);
9098 data = PyUnicode_DATA(decimal);
9099 /* Iterate over code points */
9100 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009101 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009102 if (ch > 127) {
9103 int decimal = Py_UNICODE_TODECIMAL(ch);
9104 if (decimal >= 0)
9105 ch = '0' + decimal;
9106 }
9107 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009108 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009109 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009110}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009111/* --- Decimal Encoder ---------------------------------------------------- */
9112
Alexander Belopolsky40018472011-02-26 01:02:56 +00009113int
9114PyUnicode_EncodeDecimal(Py_UNICODE *s,
9115 Py_ssize_t length,
9116 char *output,
9117 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009118{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009119 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009120 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009121 enum PyUnicode_Kind kind;
9122 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009123
9124 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009125 PyErr_BadArgument();
9126 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009127 }
9128
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009129 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009130 if (unicode == NULL)
9131 return -1;
9132
Victor Stinner42bf7752011-11-21 22:52:58 +01009133 kind = PyUnicode_KIND(unicode);
9134 data = PyUnicode_DATA(unicode);
9135
Victor Stinnerb84d7232011-11-22 01:50:07 +01009136 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009137 PyObject *exc;
9138 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009139 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009140 Py_ssize_t startpos;
9141
9142 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009143
Benjamin Peterson29060642009-01-31 22:14:21 +00009144 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009145 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009146 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009148 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009149 decimal = Py_UNICODE_TODECIMAL(ch);
9150 if (decimal >= 0) {
9151 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009152 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009153 continue;
9154 }
9155 if (0 < ch && ch < 256) {
9156 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009157 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009158 continue;
9159 }
Victor Stinner6345be92011-11-25 20:09:01 +01009160
Victor Stinner42bf7752011-11-21 22:52:58 +01009161 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009162 exc = NULL;
9163 raise_encode_exception(&exc, "decimal", unicode,
9164 startpos, startpos+1,
9165 "invalid decimal Unicode string");
9166 Py_XDECREF(exc);
9167 Py_DECREF(unicode);
9168 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009169 }
9170 /* 0-terminate the output string */
9171 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009172 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009173 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009174}
9175
Guido van Rossumd57fd912000-03-10 22:53:23 +00009176/* --- Helpers ------------------------------------------------------------ */
9177
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009178/* helper macro to fixup start/end slice values */
9179#define ADJUST_INDICES(start, end, len) \
9180 if (end > len) \
9181 end = len; \
9182 else if (end < 0) { \
9183 end += len; \
9184 if (end < 0) \
9185 end = 0; \
9186 } \
9187 if (start < 0) { \
9188 start += len; \
9189 if (start < 0) \
9190 start = 0; \
9191 }
9192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009193static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009194any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009196 Py_ssize_t end,
9197 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009199 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009200 void *buf1, *buf2;
9201 Py_ssize_t len1, len2, result;
9202
9203 kind1 = PyUnicode_KIND(s1);
9204 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009205 if (kind1 < kind2)
9206 return -1;
9207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009208 len1 = PyUnicode_GET_LENGTH(s1);
9209 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009210 ADJUST_INDICES(start, end, len1);
9211 if (end - start < len2)
9212 return -1;
9213
9214 buf1 = PyUnicode_DATA(s1);
9215 buf2 = PyUnicode_DATA(s2);
9216 if (len2 == 1) {
9217 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9218 result = findchar((const char *)buf1 + kind1*start,
9219 kind1, end - start, ch, direction);
9220 if (result == -1)
9221 return -1;
9222 else
9223 return start + result;
9224 }
9225
9226 if (kind2 != kind1) {
9227 buf2 = _PyUnicode_AsKind(s2, kind1);
9228 if (!buf2)
9229 return -2;
9230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009231
Victor Stinner794d5672011-10-10 03:21:36 +02009232 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009233 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009234 case PyUnicode_1BYTE_KIND:
9235 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9236 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9237 else
9238 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9239 break;
9240 case PyUnicode_2BYTE_KIND:
9241 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9242 break;
9243 case PyUnicode_4BYTE_KIND:
9244 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9245 break;
9246 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009247 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009248 }
9249 }
9250 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009251 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009252 case PyUnicode_1BYTE_KIND:
9253 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9254 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9255 else
9256 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9257 break;
9258 case PyUnicode_2BYTE_KIND:
9259 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9260 break;
9261 case PyUnicode_4BYTE_KIND:
9262 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9263 break;
9264 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009265 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009266 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009267 }
9268
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009269 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270 PyMem_Free(buf2);
9271
9272 return result;
9273}
9274
Victor Stinner59423e32018-11-26 13:40:01 +01009275/* _PyUnicode_InsertThousandsGrouping() helper functions */
9276#include "stringlib/localeutil.h"
9277
9278/**
9279 * InsertThousandsGrouping:
9280 * @writer: Unicode writer.
9281 * @n_buffer: Number of characters in @buffer.
9282 * @digits: Digits we're reading from. If count is non-NULL, this is unused.
9283 * @d_pos: Start of digits string.
9284 * @n_digits: The number of digits in the string, in which we want
9285 * to put the grouping chars.
9286 * @min_width: The minimum width of the digits in the output string.
9287 * Output will be zero-padded on the left to fill.
9288 * @grouping: see definition in localeconv().
9289 * @thousands_sep: see definition in localeconv().
9290 *
9291 * There are 2 modes: counting and filling. If @writer is NULL,
9292 * we are in counting mode, else filling mode.
9293 * If counting, the required buffer size is returned.
9294 * If filling, we know the buffer will be large enough, so we don't
9295 * need to pass in the buffer size.
9296 * Inserts thousand grouping characters (as defined by grouping and
9297 * thousands_sep) into @writer.
9298 *
9299 * Return value: -1 on error, number of characters otherwise.
9300 **/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009302_PyUnicode_InsertThousandsGrouping(
Victor Stinner59423e32018-11-26 13:40:01 +01009303 _PyUnicodeWriter *writer,
Victor Stinner41a863c2012-02-24 00:37:51 +01009304 Py_ssize_t n_buffer,
Victor Stinner59423e32018-11-26 13:40:01 +01009305 PyObject *digits,
9306 Py_ssize_t d_pos,
9307 Py_ssize_t n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009308 Py_ssize_t min_width,
Victor Stinner59423e32018-11-26 13:40:01 +01009309 const char *grouping,
9310 PyObject *thousands_sep,
Victor Stinner41a863c2012-02-24 00:37:51 +01009311 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009312{
Xtreak3f7983a2019-01-07 20:39:14 +05309313 min_width = Py_MAX(0, min_width);
Victor Stinner59423e32018-11-26 13:40:01 +01009314 if (writer) {
9315 assert(digits != NULL);
9316 assert(maxchar == NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009317 }
9318 else {
Victor Stinner59423e32018-11-26 13:40:01 +01009319 assert(digits == NULL);
9320 assert(maxchar != NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009321 }
Victor Stinner59423e32018-11-26 13:40:01 +01009322 assert(0 <= d_pos);
9323 assert(0 <= n_digits);
Victor Stinner59423e32018-11-26 13:40:01 +01009324 assert(grouping != NULL);
9325
9326 if (digits != NULL) {
9327 if (PyUnicode_READY(digits) == -1) {
9328 return -1;
Victor Stinner90f50d42012-02-24 01:44:47 +01009329 }
Victor Stinner59423e32018-11-26 13:40:01 +01009330 }
9331 if (PyUnicode_READY(thousands_sep) == -1) {
9332 return -1;
Victor Stinner41a863c2012-02-24 00:37:51 +01009333 }
9334
Victor Stinner59423e32018-11-26 13:40:01 +01009335 Py_ssize_t count = 0;
9336 Py_ssize_t n_zeros;
9337 int loop_broken = 0;
9338 int use_separator = 0; /* First time through, don't append the
9339 separator. They only go between
9340 groups. */
9341 Py_ssize_t buffer_pos;
9342 Py_ssize_t digits_pos;
9343 Py_ssize_t len;
9344 Py_ssize_t n_chars;
9345 Py_ssize_t remaining = n_digits; /* Number of chars remaining to
9346 be looked at */
9347 /* A generator that returns all of the grouping widths, until it
9348 returns 0. */
9349 GroupGenerator groupgen;
9350 GroupGenerator_init(&groupgen, grouping);
9351 const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9352
9353 /* if digits are not grouped, thousands separator
9354 should be an empty string */
9355 assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
9356
9357 digits_pos = d_pos + n_digits;
9358 if (writer) {
9359 buffer_pos = writer->pos + n_buffer;
9360 assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
9361 assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009362 }
Victor Stinner59423e32018-11-26 13:40:01 +01009363 else {
9364 buffer_pos = n_buffer;
Victor Stinner90f50d42012-02-24 01:44:47 +01009365 }
Victor Stinner59423e32018-11-26 13:40:01 +01009366
9367 if (!writer) {
Victor Stinner41a863c2012-02-24 00:37:51 +01009368 *maxchar = 127;
Victor Stinner41a863c2012-02-24 00:37:51 +01009369 }
Victor Stinner59423e32018-11-26 13:40:01 +01009370
9371 while ((len = GroupGenerator_next(&groupgen)) > 0) {
9372 len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
9373 n_zeros = Py_MAX(0, len - remaining);
9374 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9375
9376 /* Use n_zero zero's and n_chars chars */
9377
9378 /* Count only, don't do anything. */
9379 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9380
9381 /* Copy into the writer. */
9382 InsertThousandsGrouping_fill(writer, &buffer_pos,
9383 digits, &digits_pos,
9384 n_chars, n_zeros,
9385 use_separator ? thousands_sep : NULL,
9386 thousands_sep_len, maxchar);
9387
9388 /* Use a separator next time. */
9389 use_separator = 1;
9390
9391 remaining -= n_chars;
9392 min_width -= len;
9393
9394 if (remaining <= 0 && min_width <= 0) {
9395 loop_broken = 1;
9396 break;
9397 }
9398 min_width -= thousands_sep_len;
9399 }
9400 if (!loop_broken) {
9401 /* We left the loop without using a break statement. */
9402
9403 len = Py_MAX(Py_MAX(remaining, min_width), 1);
9404 n_zeros = Py_MAX(0, len - remaining);
9405 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9406
9407 /* Use n_zero zero's and n_chars chars */
9408 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9409
9410 /* Copy into the writer. */
9411 InsertThousandsGrouping_fill(writer, &buffer_pos,
9412 digits, &digits_pos,
9413 n_chars, n_zeros,
9414 use_separator ? thousands_sep : NULL,
9415 thousands_sep_len, maxchar);
9416 }
9417 return count;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418}
9419
9420
Alexander Belopolsky40018472011-02-26 01:02:56 +00009421Py_ssize_t
9422PyUnicode_Count(PyObject *str,
9423 PyObject *substr,
9424 Py_ssize_t start,
9425 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009427 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009428 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 void *buf1 = NULL, *buf2 = NULL;
9430 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009431
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009432 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009433 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009434
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009435 kind1 = PyUnicode_KIND(str);
9436 kind2 = PyUnicode_KIND(substr);
9437 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009438 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009439
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009440 len1 = PyUnicode_GET_LENGTH(str);
9441 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009443 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009444 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009445
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009446 buf1 = PyUnicode_DATA(str);
9447 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009448 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009449 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009450 if (!buf2)
9451 goto onError;
9452 }
9453
9454 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009456 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009457 result = asciilib_count(
9458 ((Py_UCS1*)buf1) + start, end - start,
9459 buf2, len2, PY_SSIZE_T_MAX
9460 );
9461 else
9462 result = ucs1lib_count(
9463 ((Py_UCS1*)buf1) + start, end - start,
9464 buf2, len2, PY_SSIZE_T_MAX
9465 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 break;
9467 case PyUnicode_2BYTE_KIND:
9468 result = ucs2lib_count(
9469 ((Py_UCS2*)buf1) + start, end - start,
9470 buf2, len2, PY_SSIZE_T_MAX
9471 );
9472 break;
9473 case PyUnicode_4BYTE_KIND:
9474 result = ucs4lib_count(
9475 ((Py_UCS4*)buf1) + start, end - start,
9476 buf2, len2, PY_SSIZE_T_MAX
9477 );
9478 break;
9479 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009480 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009482
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009483 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 PyMem_Free(buf2);
9485
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009488 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489 PyMem_Free(buf2);
9490 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491}
9492
Alexander Belopolsky40018472011-02-26 01:02:56 +00009493Py_ssize_t
9494PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009495 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009496 Py_ssize_t start,
9497 Py_ssize_t end,
9498 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009500 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009501 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009502
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009503 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009504}
9505
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506Py_ssize_t
9507PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9508 Py_ssize_t start, Py_ssize_t end,
9509 int direction)
9510{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009511 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009512 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009513 if (PyUnicode_READY(str) == -1)
9514 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009515 len = PyUnicode_GET_LENGTH(str);
9516 ADJUST_INDICES(start, end, len);
9517 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009518 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009520 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9521 kind, end-start, ch, direction);
9522 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009523 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009524 else
9525 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526}
9527
Alexander Belopolsky40018472011-02-26 01:02:56 +00009528static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009529tailmatch(PyObject *self,
9530 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009531 Py_ssize_t start,
9532 Py_ssize_t end,
9533 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 int kind_self;
9536 int kind_sub;
9537 void *data_self;
9538 void *data_sub;
9539 Py_ssize_t offset;
9540 Py_ssize_t i;
9541 Py_ssize_t end_sub;
9542
9543 if (PyUnicode_READY(self) == -1 ||
9544 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009545 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009547 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9548 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009549 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009550 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009552 if (PyUnicode_GET_LENGTH(substring) == 0)
9553 return 1;
9554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009555 kind_self = PyUnicode_KIND(self);
9556 data_self = PyUnicode_DATA(self);
9557 kind_sub = PyUnicode_KIND(substring);
9558 data_sub = PyUnicode_DATA(substring);
9559 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9560
9561 if (direction > 0)
9562 offset = end;
9563 else
9564 offset = start;
9565
9566 if (PyUnicode_READ(kind_self, data_self, offset) ==
9567 PyUnicode_READ(kind_sub, data_sub, 0) &&
9568 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9569 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9570 /* If both are of the same kind, memcmp is sufficient */
9571 if (kind_self == kind_sub) {
9572 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009573 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 data_sub,
9575 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009576 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009577 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009578 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009579 else {
9580 /* We do not need to compare 0 and len(substring)-1 because
9581 the if statement above ensured already that they are equal
9582 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009583 for (i = 1; i < end_sub; ++i) {
9584 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9585 PyUnicode_READ(kind_sub, data_sub, i))
9586 return 0;
9587 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009588 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009589 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009590 }
9591
9592 return 0;
9593}
9594
Alexander Belopolsky40018472011-02-26 01:02:56 +00009595Py_ssize_t
9596PyUnicode_Tailmatch(PyObject *str,
9597 PyObject *substr,
9598 Py_ssize_t start,
9599 Py_ssize_t end,
9600 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009601{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009602 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009603 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009604
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009605 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009606}
9607
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009608static PyObject *
9609ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009610{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009611 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9612 char *resdata, *data = PyUnicode_DATA(self);
9613 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009614
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009615 res = PyUnicode_New(len, 127);
9616 if (res == NULL)
9617 return NULL;
9618 resdata = PyUnicode_DATA(res);
9619 if (lower)
9620 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009621 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009622 _Py_bytes_upper(resdata, data, len);
9623 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009624}
9625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009626static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009627handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009628{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009629 Py_ssize_t j;
9630 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009631 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009632 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009633
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009634 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9635
9636 where ! is a negation and \p{xxx} is a character with property xxx.
9637 */
9638 for (j = i - 1; j >= 0; j--) {
9639 c = PyUnicode_READ(kind, data, j);
9640 if (!_PyUnicode_IsCaseIgnorable(c))
9641 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009642 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009643 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9644 if (final_sigma) {
9645 for (j = i + 1; j < length; j++) {
9646 c = PyUnicode_READ(kind, data, j);
9647 if (!_PyUnicode_IsCaseIgnorable(c))
9648 break;
9649 }
9650 final_sigma = j == length || !_PyUnicode_IsCased(c);
9651 }
9652 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009653}
9654
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009655static int
9656lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9657 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009658{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659 /* Obscure special case. */
9660 if (c == 0x3A3) {
9661 mapped[0] = handle_capital_sigma(kind, data, length, i);
9662 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009663 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009664 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009665}
9666
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009667static Py_ssize_t
9668do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670 Py_ssize_t i, k = 0;
9671 int n_res, j;
9672 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009673
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009674 c = PyUnicode_READ(kind, data, 0);
9675 n_res = _PyUnicode_ToUpperFull(c, mapped);
9676 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009677 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009678 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009679 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009680 for (i = 1; i < length; i++) {
9681 c = PyUnicode_READ(kind, data, i);
9682 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9683 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009684 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009685 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009686 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009687 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009688 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009689}
9690
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691static Py_ssize_t
9692do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9693 Py_ssize_t i, k = 0;
9694
9695 for (i = 0; i < length; i++) {
9696 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9697 int n_res, j;
9698 if (Py_UNICODE_ISUPPER(c)) {
9699 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9700 }
9701 else if (Py_UNICODE_ISLOWER(c)) {
9702 n_res = _PyUnicode_ToUpperFull(c, mapped);
9703 }
9704 else {
9705 n_res = 1;
9706 mapped[0] = c;
9707 }
9708 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009709 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009710 res[k++] = mapped[j];
9711 }
9712 }
9713 return k;
9714}
9715
9716static Py_ssize_t
9717do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9718 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009719{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009720 Py_ssize_t i, k = 0;
9721
9722 for (i = 0; i < length; i++) {
9723 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9724 int n_res, j;
9725 if (lower)
9726 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9727 else
9728 n_res = _PyUnicode_ToUpperFull(c, mapped);
9729 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009730 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009731 res[k++] = mapped[j];
9732 }
9733 }
9734 return k;
9735}
9736
9737static Py_ssize_t
9738do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9739{
9740 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9741}
9742
9743static Py_ssize_t
9744do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9745{
9746 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9747}
9748
Benjamin Petersone51757f2012-01-12 21:10:29 -05009749static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009750do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9751{
9752 Py_ssize_t i, k = 0;
9753
9754 for (i = 0; i < length; i++) {
9755 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9756 Py_UCS4 mapped[3];
9757 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9758 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009759 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009760 res[k++] = mapped[j];
9761 }
9762 }
9763 return k;
9764}
9765
9766static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009767do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9768{
9769 Py_ssize_t i, k = 0;
9770 int previous_is_cased;
9771
9772 previous_is_cased = 0;
9773 for (i = 0; i < length; i++) {
9774 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9775 Py_UCS4 mapped[3];
9776 int n_res, j;
9777
9778 if (previous_is_cased)
9779 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9780 else
9781 n_res = _PyUnicode_ToTitleFull(c, mapped);
9782
9783 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009784 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009785 res[k++] = mapped[j];
9786 }
9787
9788 previous_is_cased = _PyUnicode_IsCased(c);
9789 }
9790 return k;
9791}
9792
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009793static PyObject *
9794case_operation(PyObject *self,
9795 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9796{
9797 PyObject *res = NULL;
9798 Py_ssize_t length, newlength = 0;
9799 int kind, outkind;
9800 void *data, *outdata;
9801 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9802
Benjamin Petersoneea48462012-01-16 14:28:50 -05009803 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009804
9805 kind = PyUnicode_KIND(self);
9806 data = PyUnicode_DATA(self);
9807 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009808 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009809 PyErr_SetString(PyExc_OverflowError, "string is too long");
9810 return NULL;
9811 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009812 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009813 if (tmp == NULL)
9814 return PyErr_NoMemory();
9815 newlength = perform(kind, data, length, tmp, &maxchar);
9816 res = PyUnicode_New(newlength, maxchar);
9817 if (res == NULL)
9818 goto leave;
9819 tmpend = tmp + newlength;
9820 outdata = PyUnicode_DATA(res);
9821 outkind = PyUnicode_KIND(res);
9822 switch (outkind) {
9823 case PyUnicode_1BYTE_KIND:
9824 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9825 break;
9826 case PyUnicode_2BYTE_KIND:
9827 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9828 break;
9829 case PyUnicode_4BYTE_KIND:
9830 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9831 break;
9832 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009833 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009834 }
9835 leave:
9836 PyMem_FREE(tmp);
9837 return res;
9838}
9839
Tim Peters8ce9f162004-08-27 01:49:32 +00009840PyObject *
9841PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009842{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009843 PyObject *res;
9844 PyObject *fseq;
9845 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009846 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009847
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009848 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009849 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009850 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009851 }
9852
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009853 /* NOTE: the following code can't call back into Python code,
9854 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009855 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009856
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009857 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009858 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009859 res = _PyUnicode_JoinArray(separator, items, seqlen);
9860 Py_DECREF(fseq);
9861 return res;
9862}
9863
9864PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009865_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009866{
9867 PyObject *res = NULL; /* the result */
9868 PyObject *sep = NULL;
9869 Py_ssize_t seplen;
9870 PyObject *item;
9871 Py_ssize_t sz, i, res_offset;
9872 Py_UCS4 maxchar;
9873 Py_UCS4 item_maxchar;
9874 int use_memcpy;
9875 unsigned char *res_data = NULL, *sep_data = NULL;
9876 PyObject *last_obj;
9877 unsigned int kind = 0;
9878
Tim Peters05eba1f2004-08-27 21:32:02 +00009879 /* If empty sequence, return u"". */
9880 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009881 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009882 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009883
Tim Peters05eba1f2004-08-27 21:32:02 +00009884 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009885 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009886 if (seqlen == 1) {
9887 if (PyUnicode_CheckExact(items[0])) {
9888 res = items[0];
9889 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009890 return res;
9891 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009892 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009893 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009894 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009895 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009896 /* Set up sep and seplen */
9897 if (separator == NULL) {
9898 /* fall back to a blank space separator */
9899 sep = PyUnicode_FromOrdinal(' ');
9900 if (!sep)
9901 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009902 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009903 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009904 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009905 else {
9906 if (!PyUnicode_Check(separator)) {
9907 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009908 "separator: expected str instance,"
9909 " %.80s found",
9910 Py_TYPE(separator)->tp_name);
Victor Stinneracf47b82011-10-06 12:32:37 +02009911 goto onError;
9912 }
9913 if (PyUnicode_READY(separator))
9914 goto onError;
9915 sep = separator;
9916 seplen = PyUnicode_GET_LENGTH(separator);
9917 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9918 /* inc refcount to keep this code path symmetric with the
9919 above case of a blank separator */
9920 Py_INCREF(sep);
9921 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009922 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009923 }
9924
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009925 /* There are at least two things to join, or else we have a subclass
9926 * of str in the sequence.
9927 * Do a pre-pass to figure out the total amount of space we'll
9928 * need (sz), and see whether all argument are strings.
9929 */
9930 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009931#ifdef Py_DEBUG
9932 use_memcpy = 0;
9933#else
9934 use_memcpy = 1;
9935#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009936 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009937 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009938 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009939 if (!PyUnicode_Check(item)) {
9940 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009941 "sequence item %zd: expected str instance,"
9942 " %.80s found",
9943 i, Py_TYPE(item)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009944 goto onError;
9945 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009946 if (PyUnicode_READY(item) == -1)
9947 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009948 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009950 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009951 if (i != 0) {
9952 add_sz += seplen;
9953 }
9954 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009955 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009956 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009957 goto onError;
9958 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009959 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009960 if (use_memcpy && last_obj != NULL) {
9961 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9962 use_memcpy = 0;
9963 }
9964 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009965 }
Tim Petersced69f82003-09-16 20:30:58 +00009966
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009967 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009968 if (res == NULL)
9969 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009970
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009971 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009972#ifdef Py_DEBUG
9973 use_memcpy = 0;
9974#else
9975 if (use_memcpy) {
9976 res_data = PyUnicode_1BYTE_DATA(res);
9977 kind = PyUnicode_KIND(res);
9978 if (seplen != 0)
9979 sep_data = PyUnicode_1BYTE_DATA(sep);
9980 }
9981#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009982 if (use_memcpy) {
9983 for (i = 0; i < seqlen; ++i) {
9984 Py_ssize_t itemlen;
9985 item = items[i];
9986
9987 /* Copy item, and maybe the separator. */
9988 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009989 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009990 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009991 kind * seplen);
9992 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009993 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009994
9995 itemlen = PyUnicode_GET_LENGTH(item);
9996 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009997 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009998 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009999 kind * itemlen);
10000 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010001 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010002 }
10003 assert(res_data == PyUnicode_1BYTE_DATA(res)
10004 + kind * PyUnicode_GET_LENGTH(res));
10005 }
10006 else {
10007 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10008 Py_ssize_t itemlen;
10009 item = items[i];
10010
10011 /* Copy item, and maybe the separator. */
10012 if (i && seplen != 0) {
10013 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10014 res_offset += seplen;
10015 }
10016
10017 itemlen = PyUnicode_GET_LENGTH(item);
10018 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010019 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010020 res_offset += itemlen;
10021 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010022 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010023 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010024 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010025
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010027 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010029
Benjamin Peterson29060642009-01-31 22:14:21 +000010030 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010032 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010033 return NULL;
10034}
10035
Victor Stinnerd3f08822012-05-29 12:57:52 +020010036void
10037_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10038 Py_UCS4 fill_char)
10039{
10040 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Victor Stinner163403a2018-11-27 12:41:17 +010010041 void *data = PyUnicode_DATA(unicode);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010042 assert(PyUnicode_IS_READY(unicode));
10043 assert(unicode_modifiable(unicode));
10044 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10045 assert(start >= 0);
10046 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner59423e32018-11-26 13:40:01 +010010047 unicode_fill(kind, data, fill_char, start, length);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010048}
10049
Victor Stinner3fe55312012-01-04 00:33:50 +010010050Py_ssize_t
10051PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10052 Py_UCS4 fill_char)
10053{
10054 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010055
10056 if (!PyUnicode_Check(unicode)) {
10057 PyErr_BadInternalCall();
10058 return -1;
10059 }
10060 if (PyUnicode_READY(unicode) == -1)
10061 return -1;
10062 if (unicode_check_modifiable(unicode))
10063 return -1;
10064
Victor Stinnerd3f08822012-05-29 12:57:52 +020010065 if (start < 0) {
10066 PyErr_SetString(PyExc_IndexError, "string index out of range");
10067 return -1;
10068 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010069 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10070 PyErr_SetString(PyExc_ValueError,
10071 "fill character is bigger than "
10072 "the string maximum character");
10073 return -1;
10074 }
10075
10076 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10077 length = Py_MIN(maxlen, length);
10078 if (length <= 0)
10079 return 0;
10080
Victor Stinnerd3f08822012-05-29 12:57:52 +020010081 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010082 return length;
10083}
10084
Victor Stinner9310abb2011-10-05 00:59:23 +020010085static PyObject *
10086pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010087 Py_ssize_t left,
10088 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010090{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010091 PyObject *u;
10092 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010093 int kind;
10094 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010095
10096 if (left < 0)
10097 left = 0;
10098 if (right < 0)
10099 right = 0;
10100
Victor Stinnerc4b49542011-12-11 22:44:26 +010010101 if (left == 0 && right == 0)
10102 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010103
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10105 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010106 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10107 return NULL;
10108 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010110 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010112 if (!u)
10113 return NULL;
10114
10115 kind = PyUnicode_KIND(u);
10116 data = PyUnicode_DATA(u);
10117 if (left)
Victor Stinner59423e32018-11-26 13:40:01 +010010118 unicode_fill(kind, data, fill, 0, left);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010119 if (right)
Victor Stinner59423e32018-11-26 13:40:01 +010010120 unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010121 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010122 assert(_PyUnicode_CheckConsistency(u, 1));
10123 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010124}
10125
Alexander Belopolsky40018472011-02-26 01:02:56 +000010126PyObject *
10127PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010128{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010129 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010130
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010131 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010132 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133
Benjamin Petersonead6b532011-12-20 17:23:42 -060010134 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010136 if (PyUnicode_IS_ASCII(string))
10137 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010138 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010139 PyUnicode_GET_LENGTH(string), keepends);
10140 else
10141 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010142 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010143 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 break;
10145 case PyUnicode_2BYTE_KIND:
10146 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010147 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 PyUnicode_GET_LENGTH(string), keepends);
10149 break;
10150 case PyUnicode_4BYTE_KIND:
10151 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010152 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 PyUnicode_GET_LENGTH(string), keepends);
10154 break;
10155 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010156 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010158 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010159}
10160
Alexander Belopolsky40018472011-02-26 01:02:56 +000010161static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010162split(PyObject *self,
10163 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010164 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010165{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010166 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010167 void *buf1, *buf2;
10168 Py_ssize_t len1, len2;
10169 PyObject* out;
10170
Guido van Rossumd57fd912000-03-10 22:53:23 +000010171 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010172 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010174 if (PyUnicode_READY(self) == -1)
10175 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010176
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010178 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010180 if (PyUnicode_IS_ASCII(self))
10181 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010182 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010183 PyUnicode_GET_LENGTH(self), maxcount
10184 );
10185 else
10186 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010187 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010188 PyUnicode_GET_LENGTH(self), maxcount
10189 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 case PyUnicode_2BYTE_KIND:
10191 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010192 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 PyUnicode_GET_LENGTH(self), maxcount
10194 );
10195 case PyUnicode_4BYTE_KIND:
10196 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010197 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 PyUnicode_GET_LENGTH(self), maxcount
10199 );
10200 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010201 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 }
10203
10204 if (PyUnicode_READY(substring) == -1)
10205 return NULL;
10206
10207 kind1 = PyUnicode_KIND(self);
10208 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 len1 = PyUnicode_GET_LENGTH(self);
10210 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010211 if (kind1 < kind2 || len1 < len2) {
10212 out = PyList_New(1);
10213 if (out == NULL)
10214 return NULL;
10215 Py_INCREF(self);
10216 PyList_SET_ITEM(out, 0, self);
10217 return out;
10218 }
10219 buf1 = PyUnicode_DATA(self);
10220 buf2 = PyUnicode_DATA(substring);
10221 if (kind2 != kind1) {
10222 buf2 = _PyUnicode_AsKind(substring, kind1);
10223 if (!buf2)
10224 return NULL;
10225 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010227 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010229 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10230 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010231 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010232 else
10233 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010234 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 break;
10236 case PyUnicode_2BYTE_KIND:
10237 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010238 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 break;
10240 case PyUnicode_4BYTE_KIND:
10241 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010242 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 break;
10244 default:
10245 out = NULL;
10246 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010247 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010248 PyMem_Free(buf2);
10249 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010250}
10251
Alexander Belopolsky40018472011-02-26 01:02:56 +000010252static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010253rsplit(PyObject *self,
10254 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010255 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010256{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010257 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 void *buf1, *buf2;
10259 Py_ssize_t len1, len2;
10260 PyObject* out;
10261
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010262 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010263 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010264
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010265 if (PyUnicode_READY(self) == -1)
10266 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010269 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010271 if (PyUnicode_IS_ASCII(self))
10272 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010273 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274 PyUnicode_GET_LENGTH(self), maxcount
10275 );
10276 else
10277 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010278 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010279 PyUnicode_GET_LENGTH(self), maxcount
10280 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 case PyUnicode_2BYTE_KIND:
10282 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010283 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 PyUnicode_GET_LENGTH(self), maxcount
10285 );
10286 case PyUnicode_4BYTE_KIND:
10287 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010288 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 PyUnicode_GET_LENGTH(self), maxcount
10290 );
10291 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010292 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 }
10294
10295 if (PyUnicode_READY(substring) == -1)
10296 return NULL;
10297
10298 kind1 = PyUnicode_KIND(self);
10299 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 len1 = PyUnicode_GET_LENGTH(self);
10301 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010302 if (kind1 < kind2 || len1 < len2) {
10303 out = PyList_New(1);
10304 if (out == NULL)
10305 return NULL;
10306 Py_INCREF(self);
10307 PyList_SET_ITEM(out, 0, self);
10308 return out;
10309 }
10310 buf1 = PyUnicode_DATA(self);
10311 buf2 = PyUnicode_DATA(substring);
10312 if (kind2 != kind1) {
10313 buf2 = _PyUnicode_AsKind(substring, kind1);
10314 if (!buf2)
10315 return NULL;
10316 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010317
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010318 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010320 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10321 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010322 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010323 else
10324 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010325 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 break;
10327 case PyUnicode_2BYTE_KIND:
10328 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010329 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 break;
10331 case PyUnicode_4BYTE_KIND:
10332 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010333 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010334 break;
10335 default:
10336 out = NULL;
10337 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010338 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 PyMem_Free(buf2);
10340 return out;
10341}
10342
10343static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010344anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10345 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010346{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010347 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010349 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10350 return asciilib_find(buf1, len1, buf2, len2, offset);
10351 else
10352 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 case PyUnicode_2BYTE_KIND:
10354 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10355 case PyUnicode_4BYTE_KIND:
10356 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10357 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010358 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359}
10360
10361static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010362anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10363 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010365 switch (kind) {
10366 case PyUnicode_1BYTE_KIND:
10367 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10368 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10369 else
10370 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10371 case PyUnicode_2BYTE_KIND:
10372 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10373 case PyUnicode_4BYTE_KIND:
10374 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10375 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010376 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010377}
10378
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010379static void
10380replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10381 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10382{
10383 int kind = PyUnicode_KIND(u);
10384 void *data = PyUnicode_DATA(u);
10385 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10386 if (kind == PyUnicode_1BYTE_KIND) {
10387 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10388 (Py_UCS1 *)data + len,
10389 u1, u2, maxcount);
10390 }
10391 else if (kind == PyUnicode_2BYTE_KIND) {
10392 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10393 (Py_UCS2 *)data + len,
10394 u1, u2, maxcount);
10395 }
10396 else {
10397 assert(kind == PyUnicode_4BYTE_KIND);
10398 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10399 (Py_UCS4 *)data + len,
10400 u1, u2, maxcount);
10401 }
10402}
10403
Alexander Belopolsky40018472011-02-26 01:02:56 +000010404static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405replace(PyObject *self, PyObject *str1,
10406 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010407{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408 PyObject *u;
10409 char *sbuf = PyUnicode_DATA(self);
10410 char *buf1 = PyUnicode_DATA(str1);
10411 char *buf2 = PyUnicode_DATA(str2);
10412 int srelease = 0, release1 = 0, release2 = 0;
10413 int skind = PyUnicode_KIND(self);
10414 int kind1 = PyUnicode_KIND(str1);
10415 int kind2 = PyUnicode_KIND(str2);
10416 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10417 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10418 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010419 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010420 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010421
10422 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010423 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010425 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010426
Victor Stinner59de0ee2011-10-07 10:01:28 +020010427 if (str1 == str2)
10428 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010429
Victor Stinner49a0a212011-10-12 23:46:10 +020010430 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010431 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10432 if (maxchar < maxchar_str1)
10433 /* substring too wide to be present */
10434 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010435 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10436 /* Replacing str1 with str2 may cause a maxchar reduction in the
10437 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010438 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010439 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010442 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010444 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010445 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010446 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010447 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010448 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010449
Victor Stinner69ed0f42013-04-09 21:48:24 +020010450 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010451 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010452 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010453 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010454 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010455 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010456 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010457 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010458
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010459 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10460 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010461 }
10462 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 int rkind = skind;
10464 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010465 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010466
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010467 if (kind1 < rkind) {
10468 /* widen substring */
10469 buf1 = _PyUnicode_AsKind(str1, rkind);
10470 if (!buf1) goto error;
10471 release1 = 1;
10472 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010473 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010474 if (i < 0)
10475 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 if (rkind > kind2) {
10477 /* widen replacement */
10478 buf2 = _PyUnicode_AsKind(str2, rkind);
10479 if (!buf2) goto error;
10480 release2 = 1;
10481 }
10482 else if (rkind < kind2) {
10483 /* widen self and buf1 */
10484 rkind = kind2;
10485 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010486 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 sbuf = _PyUnicode_AsKind(self, rkind);
10488 if (!sbuf) goto error;
10489 srelease = 1;
10490 buf1 = _PyUnicode_AsKind(str1, rkind);
10491 if (!buf1) goto error;
10492 release1 = 1;
10493 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010494 u = PyUnicode_New(slen, maxchar);
10495 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010497 assert(PyUnicode_KIND(u) == rkind);
10498 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010499
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010500 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010501 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010502 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010504 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010505 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010506
10507 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010508 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010509 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010510 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010511 if (i == -1)
10512 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010513 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010514 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010515 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010517 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010518 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010519 }
10520 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010522 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 int rkind = skind;
10524 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010525
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010526 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010527 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010528 buf1 = _PyUnicode_AsKind(str1, rkind);
10529 if (!buf1) goto error;
10530 release1 = 1;
10531 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010532 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010533 if (n == 0)
10534 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010536 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 buf2 = _PyUnicode_AsKind(str2, rkind);
10538 if (!buf2) goto error;
10539 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010540 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010542 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 rkind = kind2;
10544 sbuf = _PyUnicode_AsKind(self, rkind);
10545 if (!sbuf) goto error;
10546 srelease = 1;
10547 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010548 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 buf1 = _PyUnicode_AsKind(str1, rkind);
10550 if (!buf1) goto error;
10551 release1 = 1;
10552 }
10553 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10554 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010555 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 PyErr_SetString(PyExc_OverflowError,
10557 "replace string is too long");
10558 goto error;
10559 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010560 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010561 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010562 _Py_INCREF_UNICODE_EMPTY();
10563 if (!unicode_empty)
10564 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010565 u = unicode_empty;
10566 goto done;
10567 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010568 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 PyErr_SetString(PyExc_OverflowError,
10570 "replace string is too long");
10571 goto error;
10572 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010573 u = PyUnicode_New(new_size, maxchar);
10574 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010576 assert(PyUnicode_KIND(u) == rkind);
10577 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 ires = i = 0;
10579 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010580 while (n-- > 0) {
10581 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010582 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010583 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010584 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010585 if (j == -1)
10586 break;
10587 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010588 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010589 memcpy(res + rkind * ires,
10590 sbuf + rkind * i,
10591 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593 }
10594 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010596 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010598 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010602 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010604 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010605 memcpy(res + rkind * ires,
10606 sbuf + rkind * i,
10607 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010608 }
10609 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010610 /* interleave */
10611 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010612 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010613 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010614 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010616 if (--n <= 0)
10617 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010618 memcpy(res + rkind * ires,
10619 sbuf + rkind * i,
10620 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 ires++;
10622 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010623 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010624 memcpy(res + rkind * ires,
10625 sbuf + rkind * i,
10626 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010627 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010628 }
10629
10630 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010631 unicode_adjust_maxchar(&u);
10632 if (u == NULL)
10633 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010634 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010635
10636 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010637 if (srelease)
10638 PyMem_FREE(sbuf);
10639 if (release1)
10640 PyMem_FREE(buf1);
10641 if (release2)
10642 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010643 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010645
Benjamin Peterson29060642009-01-31 22:14:21 +000010646 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010647 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648 if (srelease)
10649 PyMem_FREE(sbuf);
10650 if (release1)
10651 PyMem_FREE(buf1);
10652 if (release2)
10653 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010654 return unicode_result_unchanged(self);
10655
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 error:
10657 if (srelease && sbuf)
10658 PyMem_FREE(sbuf);
10659 if (release1 && buf1)
10660 PyMem_FREE(buf1);
10661 if (release2 && buf2)
10662 PyMem_FREE(buf2);
10663 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664}
10665
10666/* --- Unicode Object Methods --------------------------------------------- */
10667
INADA Naoki3ae20562017-01-16 20:41:20 +090010668/*[clinic input]
10669str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010670
INADA Naoki3ae20562017-01-16 20:41:20 +090010671Return a version of the string where each word is titlecased.
10672
10673More specifically, words start with uppercased characters and all remaining
10674cased characters have lower case.
10675[clinic start generated code]*/
10676
10677static PyObject *
10678unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010679/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010680{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010681 if (PyUnicode_READY(self) == -1)
10682 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010683 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010684}
10685
INADA Naoki3ae20562017-01-16 20:41:20 +090010686/*[clinic input]
10687str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010688
INADA Naoki3ae20562017-01-16 20:41:20 +090010689Return a capitalized version of the string.
10690
10691More specifically, make the first character have upper case and the rest lower
10692case.
10693[clinic start generated code]*/
10694
10695static PyObject *
10696unicode_capitalize_impl(PyObject *self)
10697/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010698{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010699 if (PyUnicode_READY(self) == -1)
10700 return NULL;
10701 if (PyUnicode_GET_LENGTH(self) == 0)
10702 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010703 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010704}
10705
INADA Naoki3ae20562017-01-16 20:41:20 +090010706/*[clinic input]
10707str.casefold as unicode_casefold
10708
10709Return a version of the string suitable for caseless comparisons.
10710[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010711
10712static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010713unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010714/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010715{
10716 if (PyUnicode_READY(self) == -1)
10717 return NULL;
10718 if (PyUnicode_IS_ASCII(self))
10719 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010720 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010721}
10722
10723
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010724/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010725
10726static int
10727convert_uc(PyObject *obj, void *addr)
10728{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010729 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010730
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010731 if (!PyUnicode_Check(obj)) {
10732 PyErr_Format(PyExc_TypeError,
10733 "The fill character must be a unicode character, "
Victor Stinner998b8062018-09-12 00:23:25 +020010734 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010735 return 0;
10736 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010737 if (PyUnicode_READY(obj) < 0)
10738 return 0;
10739 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010740 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010741 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010742 return 0;
10743 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010744 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010745 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010746}
10747
INADA Naoki3ae20562017-01-16 20:41:20 +090010748/*[clinic input]
10749str.center as unicode_center
10750
10751 width: Py_ssize_t
10752 fillchar: Py_UCS4 = ' '
10753 /
10754
10755Return a centered string of length width.
10756
10757Padding is done using the specified fill character (default is a space).
10758[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010759
10760static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010761unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10762/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010764 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010765
Benjamin Petersonbac79492012-01-14 13:34:47 -050010766 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767 return NULL;
10768
Victor Stinnerc4b49542011-12-11 22:44:26 +010010769 if (PyUnicode_GET_LENGTH(self) >= width)
10770 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010771
Victor Stinnerc4b49542011-12-11 22:44:26 +010010772 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773 left = marg / 2 + (marg & width & 1);
10774
Victor Stinner9310abb2011-10-05 00:59:23 +020010775 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776}
10777
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010778/* This function assumes that str1 and str2 are readied by the caller. */
10779
Marc-André Lemburge5034372000-08-08 08:04:29 +000010780static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010781unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010782{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010783#define COMPARE(TYPE1, TYPE2) \
10784 do { \
10785 TYPE1* p1 = (TYPE1 *)data1; \
10786 TYPE2* p2 = (TYPE2 *)data2; \
10787 TYPE1* end = p1 + len; \
10788 Py_UCS4 c1, c2; \
10789 for (; p1 != end; p1++, p2++) { \
10790 c1 = *p1; \
10791 c2 = *p2; \
10792 if (c1 != c2) \
10793 return (c1 < c2) ? -1 : 1; \
10794 } \
10795 } \
10796 while (0)
10797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010798 int kind1, kind2;
10799 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010800 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 kind1 = PyUnicode_KIND(str1);
10803 kind2 = PyUnicode_KIND(str2);
10804 data1 = PyUnicode_DATA(str1);
10805 data2 = PyUnicode_DATA(str2);
10806 len1 = PyUnicode_GET_LENGTH(str1);
10807 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010808 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010809
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010810 switch(kind1) {
10811 case PyUnicode_1BYTE_KIND:
10812 {
10813 switch(kind2) {
10814 case PyUnicode_1BYTE_KIND:
10815 {
10816 int cmp = memcmp(data1, data2, len);
10817 /* normalize result of memcmp() into the range [-1; 1] */
10818 if (cmp < 0)
10819 return -1;
10820 if (cmp > 0)
10821 return 1;
10822 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010823 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010824 case PyUnicode_2BYTE_KIND:
10825 COMPARE(Py_UCS1, Py_UCS2);
10826 break;
10827 case PyUnicode_4BYTE_KIND:
10828 COMPARE(Py_UCS1, Py_UCS4);
10829 break;
10830 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010831 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010832 }
10833 break;
10834 }
10835 case PyUnicode_2BYTE_KIND:
10836 {
10837 switch(kind2) {
10838 case PyUnicode_1BYTE_KIND:
10839 COMPARE(Py_UCS2, Py_UCS1);
10840 break;
10841 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010842 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010843 COMPARE(Py_UCS2, Py_UCS2);
10844 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010845 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010846 case PyUnicode_4BYTE_KIND:
10847 COMPARE(Py_UCS2, Py_UCS4);
10848 break;
10849 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010850 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010851 }
10852 break;
10853 }
10854 case PyUnicode_4BYTE_KIND:
10855 {
10856 switch(kind2) {
10857 case PyUnicode_1BYTE_KIND:
10858 COMPARE(Py_UCS4, Py_UCS1);
10859 break;
10860 case PyUnicode_2BYTE_KIND:
10861 COMPARE(Py_UCS4, Py_UCS2);
10862 break;
10863 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010864 {
10865#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10866 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10867 /* normalize result of wmemcmp() into the range [-1; 1] */
10868 if (cmp < 0)
10869 return -1;
10870 if (cmp > 0)
10871 return 1;
10872#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010873 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010874#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010875 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010876 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010877 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010878 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010879 }
10880 break;
10881 }
10882 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010883 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010884 }
10885
Victor Stinner770e19e2012-10-04 22:59:45 +020010886 if (len1 == len2)
10887 return 0;
10888 if (len1 < len2)
10889 return -1;
10890 else
10891 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010892
10893#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010894}
10895
Benjamin Peterson621b4302016-09-09 13:54:34 -070010896static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010897unicode_compare_eq(PyObject *str1, PyObject *str2)
10898{
10899 int kind;
10900 void *data1, *data2;
10901 Py_ssize_t len;
10902 int cmp;
10903
Victor Stinnere5567ad2012-10-23 02:48:49 +020010904 len = PyUnicode_GET_LENGTH(str1);
10905 if (PyUnicode_GET_LENGTH(str2) != len)
10906 return 0;
10907 kind = PyUnicode_KIND(str1);
10908 if (PyUnicode_KIND(str2) != kind)
10909 return 0;
10910 data1 = PyUnicode_DATA(str1);
10911 data2 = PyUnicode_DATA(str2);
10912
10913 cmp = memcmp(data1, data2, len * kind);
10914 return (cmp == 0);
10915}
10916
10917
Alexander Belopolsky40018472011-02-26 01:02:56 +000010918int
10919PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010921 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10922 if (PyUnicode_READY(left) == -1 ||
10923 PyUnicode_READY(right) == -1)
10924 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010925
10926 /* a string is equal to itself */
10927 if (left == right)
10928 return 0;
10929
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010930 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010932 PyErr_Format(PyExc_TypeError,
10933 "Can't compare %.100s and %.100s",
10934 left->ob_type->tp_name,
10935 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936 return -1;
10937}
10938
Martin v. Löwis5b222132007-06-10 09:51:05 +000010939int
10940PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10941{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010942 Py_ssize_t i;
10943 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010944 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010945 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010946
Victor Stinner910337b2011-10-03 03:20:16 +020010947 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010948 if (!PyUnicode_IS_READY(uni)) {
10949 const wchar_t *ws = _PyUnicode_WSTR(uni);
10950 /* Compare Unicode string and source character set string */
10951 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10952 if (chr != ustr[i])
10953 return (chr < ustr[i]) ? -1 : 1;
10954 }
10955 /* This check keeps Python strings that end in '\0' from comparing equal
10956 to C strings identical up to that point. */
10957 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10958 return 1; /* uni is longer */
10959 if (ustr[i])
10960 return -1; /* str is longer */
10961 return 0;
10962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010963 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010964 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010965 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010966 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010967 size_t len, len2 = strlen(str);
10968 int cmp;
10969
10970 len = Py_MIN(len1, len2);
10971 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010972 if (cmp != 0) {
10973 if (cmp < 0)
10974 return -1;
10975 else
10976 return 1;
10977 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010978 if (len1 > len2)
10979 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010980 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010981 return -1; /* str is longer */
10982 return 0;
10983 }
10984 else {
10985 void *data = PyUnicode_DATA(uni);
10986 /* Compare Unicode string and source character set string */
10987 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010988 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010989 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10990 /* This check keeps Python strings that end in '\0' from comparing equal
10991 to C strings identical up to that point. */
10992 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10993 return 1; /* uni is longer */
10994 if (str[i])
10995 return -1; /* str is longer */
10996 return 0;
10997 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010998}
10999
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011000static int
11001non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11002{
11003 size_t i, len;
11004 const wchar_t *p;
11005 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11006 if (strlen(str) != len)
11007 return 0;
11008 p = _PyUnicode_WSTR(unicode);
11009 assert(p);
11010 for (i = 0; i < len; i++) {
11011 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011012 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011013 return 0;
11014 }
11015 return 1;
11016}
11017
11018int
11019_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11020{
11021 size_t len;
11022 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011023 assert(str);
11024#ifndef NDEBUG
11025 for (const char *p = str; *p; p++) {
11026 assert((unsigned char)*p < 128);
11027 }
11028#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011029 if (PyUnicode_READY(unicode) == -1) {
11030 /* Memory error or bad data */
11031 PyErr_Clear();
11032 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11033 }
11034 if (!PyUnicode_IS_ASCII(unicode))
11035 return 0;
11036 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11037 return strlen(str) == len &&
11038 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11039}
11040
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011041int
11042_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11043{
11044 PyObject *right_uni;
11045 Py_hash_t hash;
11046
11047 assert(_PyUnicode_CHECK(left));
11048 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011049#ifndef NDEBUG
11050 for (const char *p = right->string; *p; p++) {
11051 assert((unsigned char)*p < 128);
11052 }
11053#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011054
11055 if (PyUnicode_READY(left) == -1) {
11056 /* memory error or bad data */
11057 PyErr_Clear();
11058 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11059 }
11060
11061 if (!PyUnicode_IS_ASCII(left))
11062 return 0;
11063
11064 right_uni = _PyUnicode_FromId(right); /* borrowed */
11065 if (right_uni == NULL) {
11066 /* memory error or bad data */
11067 PyErr_Clear();
11068 return _PyUnicode_EqualToASCIIString(left, right->string);
11069 }
11070
11071 if (left == right_uni)
11072 return 1;
11073
11074 if (PyUnicode_CHECK_INTERNED(left))
11075 return 0;
11076
INADA Naoki7cc95f52018-01-28 02:07:09 +090011077 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011078 hash = _PyUnicode_HASH(left);
11079 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11080 return 0;
11081
11082 return unicode_compare_eq(left, right_uni);
11083}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011084
Alexander Belopolsky40018472011-02-26 01:02:56 +000011085PyObject *
11086PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011087{
11088 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011089
Victor Stinnere5567ad2012-10-23 02:48:49 +020011090 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11091 Py_RETURN_NOTIMPLEMENTED;
11092
11093 if (PyUnicode_READY(left) == -1 ||
11094 PyUnicode_READY(right) == -1)
11095 return NULL;
11096
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011097 if (left == right) {
11098 switch (op) {
11099 case Py_EQ:
11100 case Py_LE:
11101 case Py_GE:
11102 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011103 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011104 case Py_NE:
11105 case Py_LT:
11106 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011107 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011108 default:
11109 PyErr_BadArgument();
11110 return NULL;
11111 }
11112 }
11113 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011114 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011115 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011116 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011117 }
11118 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011119 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011120 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011121 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011122}
11123
Alexander Belopolsky40018472011-02-26 01:02:56 +000011124int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011125_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11126{
11127 return unicode_eq(aa, bb);
11128}
11129
11130int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011131PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011132{
Victor Stinner77282cb2013-04-14 19:22:47 +020011133 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134 void *buf1, *buf2;
11135 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011136 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011137
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011138 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011139 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020011140 "'in <string>' requires string as left operand, not %.100s",
11141 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011142 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011143 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011144 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011145 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011146 if (ensure_unicode(str) < 0)
11147 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011150 kind2 = PyUnicode_KIND(substr);
11151 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011152 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011153 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011154 len2 = PyUnicode_GET_LENGTH(substr);
11155 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011156 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011157 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011158 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011159 if (len2 == 1) {
11160 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11161 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011162 return result;
11163 }
11164 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011165 buf2 = _PyUnicode_AsKind(substr, kind1);
11166 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011167 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011168 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011169
Victor Stinner77282cb2013-04-14 19:22:47 +020011170 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 case PyUnicode_1BYTE_KIND:
11172 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11173 break;
11174 case PyUnicode_2BYTE_KIND:
11175 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11176 break;
11177 case PyUnicode_4BYTE_KIND:
11178 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11179 break;
11180 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011181 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011182 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011183
Victor Stinner77282cb2013-04-14 19:22:47 +020011184 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 PyMem_Free(buf2);
11186
Guido van Rossum403d68b2000-03-13 15:55:09 +000011187 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011188}
11189
Guido van Rossumd57fd912000-03-10 22:53:23 +000011190/* Concat to string or Unicode object giving a new Unicode object. */
11191
Alexander Belopolsky40018472011-02-26 01:02:56 +000011192PyObject *
11193PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011194{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011195 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011196 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011197 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011199 if (ensure_unicode(left) < 0)
11200 return NULL;
11201
11202 if (!PyUnicode_Check(right)) {
11203 PyErr_Format(PyExc_TypeError,
11204 "can only concatenate str (not \"%.200s\") to str",
11205 right->ob_type->tp_name);
11206 return NULL;
11207 }
11208 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011209 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210
11211 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011212 if (left == unicode_empty)
11213 return PyUnicode_FromObject(right);
11214 if (right == unicode_empty)
11215 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011217 left_len = PyUnicode_GET_LENGTH(left);
11218 right_len = PyUnicode_GET_LENGTH(right);
11219 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011220 PyErr_SetString(PyExc_OverflowError,
11221 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011222 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011223 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011224 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011225
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011226 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11227 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011228 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011229
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011231 result = PyUnicode_New(new_len, maxchar);
11232 if (result == NULL)
11233 return NULL;
11234 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11235 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11236 assert(_PyUnicode_CheckConsistency(result, 1));
11237 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238}
11239
Walter Dörwald1ab83302007-05-18 17:15:44 +000011240void
Victor Stinner23e56682011-10-03 03:54:37 +020011241PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011242{
Victor Stinner23e56682011-10-03 03:54:37 +020011243 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011244 Py_UCS4 maxchar, maxchar2;
11245 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011246
11247 if (p_left == NULL) {
11248 if (!PyErr_Occurred())
11249 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011250 return;
11251 }
Victor Stinner23e56682011-10-03 03:54:37 +020011252 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011253 if (right == NULL || left == NULL
11254 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011255 if (!PyErr_Occurred())
11256 PyErr_BadInternalCall();
11257 goto error;
11258 }
11259
Benjamin Petersonbac79492012-01-14 13:34:47 -050011260 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011261 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011262 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011263 goto error;
11264
Victor Stinner488fa492011-12-12 00:01:39 +010011265 /* Shortcuts */
11266 if (left == unicode_empty) {
11267 Py_DECREF(left);
11268 Py_INCREF(right);
11269 *p_left = right;
11270 return;
11271 }
11272 if (right == unicode_empty)
11273 return;
11274
11275 left_len = PyUnicode_GET_LENGTH(left);
11276 right_len = PyUnicode_GET_LENGTH(right);
11277 if (left_len > PY_SSIZE_T_MAX - right_len) {
11278 PyErr_SetString(PyExc_OverflowError,
11279 "strings are too large to concat");
11280 goto error;
11281 }
11282 new_len = left_len + right_len;
11283
11284 if (unicode_modifiable(left)
11285 && PyUnicode_CheckExact(right)
11286 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011287 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11288 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011289 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011290 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011291 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11292 {
11293 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011294 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011295 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011296
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011297 /* copy 'right' into the newly allocated area of 'left' */
11298 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011299 }
Victor Stinner488fa492011-12-12 00:01:39 +010011300 else {
11301 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11302 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011303 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011304
Victor Stinner488fa492011-12-12 00:01:39 +010011305 /* Concat the two Unicode strings */
11306 res = PyUnicode_New(new_len, maxchar);
11307 if (res == NULL)
11308 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011309 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11310 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011311 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011312 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011313 }
11314 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011315 return;
11316
11317error:
Victor Stinner488fa492011-12-12 00:01:39 +010011318 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011319}
11320
11321void
11322PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11323{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011324 PyUnicode_Append(pleft, right);
11325 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011326}
11327
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011328/*
11329Wraps stringlib_parse_args_finds() and additionally ensures that the
11330first argument is a unicode object.
11331*/
11332
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011333static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011334parse_args_finds_unicode(const char * function_name, PyObject *args,
11335 PyObject **substring,
11336 Py_ssize_t *start, Py_ssize_t *end)
11337{
11338 if(stringlib_parse_args_finds(function_name, args, substring,
11339 start, end)) {
11340 if (ensure_unicode(*substring) < 0)
11341 return 0;
11342 return 1;
11343 }
11344 return 0;
11345}
11346
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011347PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011348 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011350Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011351string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011352interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353
11354static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011355unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011357 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011358 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011359 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011361 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011362 void *buf1, *buf2;
11363 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011365 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011366 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011367
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 kind1 = PyUnicode_KIND(self);
11369 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011370 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011371 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 len1 = PyUnicode_GET_LENGTH(self);
11374 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011376 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011377 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011378
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011379 buf1 = PyUnicode_DATA(self);
11380 buf2 = PyUnicode_DATA(substring);
11381 if (kind2 != kind1) {
11382 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011383 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011384 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011385 }
11386 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 case PyUnicode_1BYTE_KIND:
11388 iresult = ucs1lib_count(
11389 ((Py_UCS1*)buf1) + start, end - start,
11390 buf2, len2, PY_SSIZE_T_MAX
11391 );
11392 break;
11393 case PyUnicode_2BYTE_KIND:
11394 iresult = ucs2lib_count(
11395 ((Py_UCS2*)buf1) + start, end - start,
11396 buf2, len2, PY_SSIZE_T_MAX
11397 );
11398 break;
11399 case PyUnicode_4BYTE_KIND:
11400 iresult = ucs4lib_count(
11401 ((Py_UCS4*)buf1) + start, end - start,
11402 buf2, len2, PY_SSIZE_T_MAX
11403 );
11404 break;
11405 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011406 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011407 }
11408
11409 result = PyLong_FromSsize_t(iresult);
11410
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011411 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414 return result;
11415}
11416
INADA Naoki3ae20562017-01-16 20:41:20 +090011417/*[clinic input]
11418str.encode as unicode_encode
11419
11420 encoding: str(c_default="NULL") = 'utf-8'
11421 The encoding in which to encode the string.
11422 errors: str(c_default="NULL") = 'strict'
11423 The error handling scheme to use for encoding errors.
11424 The default is 'strict' meaning that encoding errors raise a
11425 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11426 'xmlcharrefreplace' as well as any other name registered with
11427 codecs.register_error that can handle UnicodeEncodeErrors.
11428
11429Encode the string using the codec registered for encoding.
11430[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431
11432static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011433unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011434/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011436 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011437}
11438
INADA Naoki3ae20562017-01-16 20:41:20 +090011439/*[clinic input]
11440str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441
INADA Naoki3ae20562017-01-16 20:41:20 +090011442 tabsize: int = 8
11443
11444Return a copy where all tab characters are expanded using spaces.
11445
11446If tabsize is not given, a tab size of 8 characters is assumed.
11447[clinic start generated code]*/
11448
11449static PyObject *
11450unicode_expandtabs_impl(PyObject *self, int tabsize)
11451/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011453 Py_ssize_t i, j, line_pos, src_len, incr;
11454 Py_UCS4 ch;
11455 PyObject *u;
11456 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011457 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011458 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
Antoine Pitrou22425222011-10-04 19:10:51 +020011460 if (PyUnicode_READY(self) == -1)
11461 return NULL;
11462
Thomas Wouters7e474022000-07-16 12:04:32 +000011463 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011464 src_len = PyUnicode_GET_LENGTH(self);
11465 i = j = line_pos = 0;
11466 kind = PyUnicode_KIND(self);
11467 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011468 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011469 for (; i < src_len; i++) {
11470 ch = PyUnicode_READ(kind, src_data, i);
11471 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011472 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011473 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011474 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011476 goto overflow;
11477 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011479 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011480 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011481 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011483 goto overflow;
11484 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 if (ch == '\n' || ch == '\r')
11487 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011489 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011490 if (!found)
11491 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011492
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011494 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495 if (!u)
11496 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011497 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498
Antoine Pitroue71d5742011-10-04 15:55:09 +020011499 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500
Antoine Pitroue71d5742011-10-04 15:55:09 +020011501 for (; i < src_len; i++) {
11502 ch = PyUnicode_READ(kind, src_data, i);
11503 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011504 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011505 incr = tabsize - (line_pos % tabsize);
11506 line_pos += incr;
Victor Stinner59423e32018-11-26 13:40:01 +010011507 unicode_fill(kind, dest_data, ' ', j, incr);
Victor Stinnerda79e632012-02-22 13:37:04 +010011508 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011509 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011510 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011511 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011512 line_pos++;
11513 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011514 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011515 if (ch == '\n' || ch == '\r')
11516 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011518 }
11519 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011520 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011521
Antoine Pitroue71d5742011-10-04 15:55:09 +020011522 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011523 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11524 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525}
11526
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011527PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011528 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529\n\
11530Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011531such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532arguments start and end are interpreted as in slice notation.\n\
11533\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011534Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535
11536static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011539 /* initialize variables to prevent gcc warning */
11540 PyObject *substring = NULL;
11541 Py_ssize_t start = 0;
11542 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011543 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011545 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011548 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011551 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011552
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553 if (result == -2)
11554 return NULL;
11555
Christian Heimes217cfd12007-12-02 14:31:20 +000011556 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011557}
11558
11559static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011560unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011562 void *data;
11563 enum PyUnicode_Kind kind;
11564 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011565
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011566 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011567 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011568 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011569 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011570 if (PyUnicode_READY(self) == -1) {
11571 return NULL;
11572 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011573 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11574 PyErr_SetString(PyExc_IndexError, "string index out of range");
11575 return NULL;
11576 }
11577 kind = PyUnicode_KIND(self);
11578 data = PyUnicode_DATA(self);
11579 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011580 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581}
11582
Guido van Rossumc2504932007-09-18 19:42:40 +000011583/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011584 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011585static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011586unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011587{
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011588 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011589
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011590#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011591 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011592#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593 if (_PyUnicode_HASH(self) != -1)
11594 return _PyUnicode_HASH(self);
11595 if (PyUnicode_READY(self) == -1)
11596 return -1;
animalizea1d14252019-01-02 20:16:06 +080011597
Christian Heimes985ecdc2013-11-20 11:46:18 +010011598 x = _Py_HashBytes(PyUnicode_DATA(self),
11599 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011600 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011601 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011602}
11603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011604PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011605 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606\n\
oldkaa0735f2018-02-02 16:52:55 +080011607Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011608such that sub is contained within S[start:end]. Optional\n\
11609arguments start and end are interpreted as in slice notation.\n\
11610\n\
11611Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612
11613static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011616 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011617 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011618 PyObject *substring = NULL;
11619 Py_ssize_t start = 0;
11620 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011622 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011625 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011626 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011627
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011628 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011629
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 if (result == -2)
11631 return NULL;
11632
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633 if (result < 0) {
11634 PyErr_SetString(PyExc_ValueError, "substring not found");
11635 return NULL;
11636 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011637
Christian Heimes217cfd12007-12-02 14:31:20 +000011638 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639}
11640
INADA Naoki3ae20562017-01-16 20:41:20 +090011641/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011642str.isascii as unicode_isascii
11643
11644Return True if all characters in the string are ASCII, False otherwise.
11645
11646ASCII characters have code points in the range U+0000-U+007F.
11647Empty string is ASCII too.
11648[clinic start generated code]*/
11649
11650static PyObject *
11651unicode_isascii_impl(PyObject *self)
11652/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11653{
11654 if (PyUnicode_READY(self) == -1) {
11655 return NULL;
11656 }
11657 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11658}
11659
11660/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011661str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011662
INADA Naoki3ae20562017-01-16 20:41:20 +090011663Return True if the string is a lowercase string, False otherwise.
11664
11665A string is lowercase if all cased characters in the string are lowercase and
11666there is at least one cased character in the string.
11667[clinic start generated code]*/
11668
11669static PyObject *
11670unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011671/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011672{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673 Py_ssize_t i, length;
11674 int kind;
11675 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011676 int cased;
11677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678 if (PyUnicode_READY(self) == -1)
11679 return NULL;
11680 length = PyUnicode_GET_LENGTH(self);
11681 kind = PyUnicode_KIND(self);
11682 data = PyUnicode_DATA(self);
11683
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 if (length == 1)
11686 return PyBool_FromLong(
11687 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011688
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011689 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011691 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011692
Guido van Rossumd57fd912000-03-10 22:53:23 +000011693 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 for (i = 0; i < length; i++) {
11695 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011696
Benjamin Peterson29060642009-01-31 22:14:21 +000011697 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011698 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011699 else if (!cased && Py_UNICODE_ISLOWER(ch))
11700 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011702 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703}
11704
INADA Naoki3ae20562017-01-16 20:41:20 +090011705/*[clinic input]
11706str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707
INADA Naoki3ae20562017-01-16 20:41:20 +090011708Return True if the string is an uppercase string, False otherwise.
11709
11710A string is uppercase if all cased characters in the string are uppercase and
11711there is at least one cased character in the string.
11712[clinic start generated code]*/
11713
11714static PyObject *
11715unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011716/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 Py_ssize_t i, length;
11719 int kind;
11720 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 int cased;
11722
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 if (PyUnicode_READY(self) == -1)
11724 return NULL;
11725 length = PyUnicode_GET_LENGTH(self);
11726 kind = PyUnicode_KIND(self);
11727 data = PyUnicode_DATA(self);
11728
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011730 if (length == 1)
11731 return PyBool_FromLong(
11732 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011733
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011734 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011736 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011737
Guido van Rossumd57fd912000-03-10 22:53:23 +000011738 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739 for (i = 0; i < length; i++) {
11740 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011741
Benjamin Peterson29060642009-01-31 22:14:21 +000011742 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011743 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011744 else if (!cased && Py_UNICODE_ISUPPER(ch))
11745 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011747 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748}
11749
INADA Naoki3ae20562017-01-16 20:41:20 +090011750/*[clinic input]
11751str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752
INADA Naoki3ae20562017-01-16 20:41:20 +090011753Return True if the string is a title-cased string, False otherwise.
11754
11755In a title-cased string, upper- and title-case characters may only
11756follow uncased characters and lowercase characters only cased ones.
11757[clinic start generated code]*/
11758
11759static PyObject *
11760unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011761/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 Py_ssize_t i, length;
11764 int kind;
11765 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011766 int cased, previous_is_cased;
11767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768 if (PyUnicode_READY(self) == -1)
11769 return NULL;
11770 length = PyUnicode_GET_LENGTH(self);
11771 kind = PyUnicode_KIND(self);
11772 data = PyUnicode_DATA(self);
11773
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011775 if (length == 1) {
11776 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11777 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11778 (Py_UNICODE_ISUPPER(ch) != 0));
11779 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011780
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011781 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011783 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011784
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785 cased = 0;
11786 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011787 for (i = 0; i < length; i++) {
11788 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011789
Benjamin Peterson29060642009-01-31 22:14:21 +000011790 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11791 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011792 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011793 previous_is_cased = 1;
11794 cased = 1;
11795 }
11796 else if (Py_UNICODE_ISLOWER(ch)) {
11797 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011798 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011799 previous_is_cased = 1;
11800 cased = 1;
11801 }
11802 else
11803 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011804 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011805 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806}
11807
INADA Naoki3ae20562017-01-16 20:41:20 +090011808/*[clinic input]
11809str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810
INADA Naoki3ae20562017-01-16 20:41:20 +090011811Return True if the string is a whitespace string, False otherwise.
11812
11813A string is whitespace if all characters in the string are whitespace and there
11814is at least one character in the string.
11815[clinic start generated code]*/
11816
11817static PyObject *
11818unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011819/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 Py_ssize_t i, length;
11822 int kind;
11823 void *data;
11824
11825 if (PyUnicode_READY(self) == -1)
11826 return NULL;
11827 length = PyUnicode_GET_LENGTH(self);
11828 kind = PyUnicode_KIND(self);
11829 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011832 if (length == 1)
11833 return PyBool_FromLong(
11834 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011835
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011836 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011837 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011838 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011839
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 for (i = 0; i < length; i++) {
11841 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011842 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011843 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011844 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011845 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011846}
11847
INADA Naoki3ae20562017-01-16 20:41:20 +090011848/*[clinic input]
11849str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011850
INADA Naoki3ae20562017-01-16 20:41:20 +090011851Return True if the string is an alphabetic string, False otherwise.
11852
11853A string is alphabetic if all characters in the string are alphabetic and there
11854is at least one character in the string.
11855[clinic start generated code]*/
11856
11857static PyObject *
11858unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011859/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011860{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 Py_ssize_t i, length;
11862 int kind;
11863 void *data;
11864
11865 if (PyUnicode_READY(self) == -1)
11866 return NULL;
11867 length = PyUnicode_GET_LENGTH(self);
11868 kind = PyUnicode_KIND(self);
11869 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011870
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011871 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011872 if (length == 1)
11873 return PyBool_FromLong(
11874 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011875
11876 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011878 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011879
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 for (i = 0; i < length; i++) {
11881 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011882 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011883 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011884 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011885}
11886
INADA Naoki3ae20562017-01-16 20:41:20 +090011887/*[clinic input]
11888str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011889
INADA Naoki3ae20562017-01-16 20:41:20 +090011890Return True if the string is an alpha-numeric string, False otherwise.
11891
11892A string is alpha-numeric if all characters in the string are alpha-numeric and
11893there is at least one character in the string.
11894[clinic start generated code]*/
11895
11896static PyObject *
11897unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011898/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011899{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011900 int kind;
11901 void *data;
11902 Py_ssize_t len, i;
11903
11904 if (PyUnicode_READY(self) == -1)
11905 return NULL;
11906
11907 kind = PyUnicode_KIND(self);
11908 data = PyUnicode_DATA(self);
11909 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011910
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011911 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 if (len == 1) {
11913 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11914 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11915 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011916
11917 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011919 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011920
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011921 for (i = 0; i < len; i++) {
11922 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011923 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011924 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011925 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011926 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011927}
11928
INADA Naoki3ae20562017-01-16 20:41:20 +090011929/*[clinic input]
11930str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931
INADA Naoki3ae20562017-01-16 20:41:20 +090011932Return True if the string is a decimal string, False otherwise.
11933
11934A string is a decimal string if all characters in the string are decimal and
11935there is at least one character in the string.
11936[clinic start generated code]*/
11937
11938static PyObject *
11939unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011940/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942 Py_ssize_t i, length;
11943 int kind;
11944 void *data;
11945
11946 if (PyUnicode_READY(self) == -1)
11947 return NULL;
11948 length = PyUnicode_GET_LENGTH(self);
11949 kind = PyUnicode_KIND(self);
11950 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011951
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 if (length == 1)
11954 return PyBool_FromLong(
11955 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011957 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011958 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011959 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011960
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 for (i = 0; i < length; i++) {
11962 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011963 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011965 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966}
11967
INADA Naoki3ae20562017-01-16 20:41:20 +090011968/*[clinic input]
11969str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011970
INADA Naoki3ae20562017-01-16 20:41:20 +090011971Return True if the string is a digit string, False otherwise.
11972
11973A string is a digit string if all characters in the string are digits and there
11974is at least one character in the string.
11975[clinic start generated code]*/
11976
11977static PyObject *
11978unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011979/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 Py_ssize_t i, length;
11982 int kind;
11983 void *data;
11984
11985 if (PyUnicode_READY(self) == -1)
11986 return NULL;
11987 length = PyUnicode_GET_LENGTH(self);
11988 kind = PyUnicode_KIND(self);
11989 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011990
Guido van Rossumd57fd912000-03-10 22:53:23 +000011991 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 if (length == 1) {
11993 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11994 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11995 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011996
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011997 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011998 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011999 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 for (i = 0; i < length; i++) {
12002 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012003 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012004 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012005 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012006}
12007
INADA Naoki3ae20562017-01-16 20:41:20 +090012008/*[clinic input]
12009str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012010
INADA Naoki3ae20562017-01-16 20:41:20 +090012011Return True if the string is a numeric string, False otherwise.
12012
12013A string is numeric if all characters in the string are numeric and there is at
12014least one character in the string.
12015[clinic start generated code]*/
12016
12017static PyObject *
12018unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012019/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012020{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 Py_ssize_t i, length;
12022 int kind;
12023 void *data;
12024
12025 if (PyUnicode_READY(self) == -1)
12026 return NULL;
12027 length = PyUnicode_GET_LENGTH(self);
12028 kind = PyUnicode_KIND(self);
12029 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030
Guido van Rossumd57fd912000-03-10 22:53:23 +000012031 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 if (length == 1)
12033 return PyBool_FromLong(
12034 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012035
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012036 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012037 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012038 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 for (i = 0; i < length; i++) {
12041 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012042 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012043 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012044 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012045}
12046
Martin v. Löwis47383402007-08-15 07:32:56 +000012047int
12048PyUnicode_IsIdentifier(PyObject *self)
12049{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 int kind;
12051 void *data;
12052 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012053 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012055 if (PyUnicode_READY(self) == -1) {
12056 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012057 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058 }
12059
12060 /* Special case for empty strings */
12061 if (PyUnicode_GET_LENGTH(self) == 0)
12062 return 0;
12063 kind = PyUnicode_KIND(self);
12064 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012065
12066 /* PEP 3131 says that the first character must be in
12067 XID_Start and subsequent characters in XID_Continue,
12068 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012069 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012070 letters, digits, underscore). However, given the current
12071 definition of XID_Start and XID_Continue, it is sufficient
12072 to check just for these, except that _ must be allowed
12073 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012075 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012076 return 0;
12077
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012078 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012079 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012080 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012081 return 1;
12082}
12083
INADA Naoki3ae20562017-01-16 20:41:20 +090012084/*[clinic input]
12085str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012086
INADA Naoki3ae20562017-01-16 20:41:20 +090012087Return True if the string is a valid Python identifier, False otherwise.
12088
Sanyam Khuranaffc5a142018-10-08 12:23:32 +053012089Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012090such as "def" or "class".
INADA Naoki3ae20562017-01-16 20:41:20 +090012091[clinic start generated code]*/
12092
12093static PyObject *
12094unicode_isidentifier_impl(PyObject *self)
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012095/*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012096{
12097 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12098}
12099
INADA Naoki3ae20562017-01-16 20:41:20 +090012100/*[clinic input]
12101str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012102
INADA Naoki3ae20562017-01-16 20:41:20 +090012103Return True if the string is printable, False otherwise.
12104
12105A string is printable if all of its characters are considered printable in
12106repr() or if it is empty.
12107[clinic start generated code]*/
12108
12109static PyObject *
12110unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012111/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012112{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012113 Py_ssize_t i, length;
12114 int kind;
12115 void *data;
12116
12117 if (PyUnicode_READY(self) == -1)
12118 return NULL;
12119 length = PyUnicode_GET_LENGTH(self);
12120 kind = PyUnicode_KIND(self);
12121 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012122
12123 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012124 if (length == 1)
12125 return PyBool_FromLong(
12126 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 for (i = 0; i < length; i++) {
12129 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012130 Py_RETURN_FALSE;
12131 }
12132 }
12133 Py_RETURN_TRUE;
12134}
12135
INADA Naoki3ae20562017-01-16 20:41:20 +090012136/*[clinic input]
12137str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138
INADA Naoki3ae20562017-01-16 20:41:20 +090012139 iterable: object
12140 /
12141
12142Concatenate any number of strings.
12143
Martin Panter91a88662017-01-24 00:30:06 +000012144The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012145The result is returned as a new string.
12146
12147Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12148[clinic start generated code]*/
12149
12150static PyObject *
12151unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012152/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153{
INADA Naoki3ae20562017-01-16 20:41:20 +090012154 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155}
12156
Martin v. Löwis18e16552006-02-15 17:27:45 +000012157static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012158unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160 if (PyUnicode_READY(self) == -1)
12161 return -1;
12162 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163}
12164
INADA Naoki3ae20562017-01-16 20:41:20 +090012165/*[clinic input]
12166str.ljust as unicode_ljust
12167
12168 width: Py_ssize_t
12169 fillchar: Py_UCS4 = ' '
12170 /
12171
12172Return a left-justified string of length width.
12173
12174Padding is done using the specified fill character (default is a space).
12175[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176
12177static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012178unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12179/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012181 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012182 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183
Victor Stinnerc4b49542011-12-11 22:44:26 +010012184 if (PyUnicode_GET_LENGTH(self) >= width)
12185 return unicode_result_unchanged(self);
12186
12187 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188}
12189
INADA Naoki3ae20562017-01-16 20:41:20 +090012190/*[clinic input]
12191str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192
INADA Naoki3ae20562017-01-16 20:41:20 +090012193Return a copy of the string converted to lowercase.
12194[clinic start generated code]*/
12195
12196static PyObject *
12197unicode_lower_impl(PyObject *self)
12198/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012200 if (PyUnicode_READY(self) == -1)
12201 return NULL;
12202 if (PyUnicode_IS_ASCII(self))
12203 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012204 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205}
12206
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012207#define LEFTSTRIP 0
12208#define RIGHTSTRIP 1
12209#define BOTHSTRIP 2
12210
12211/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012212static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012213
INADA Naoki3ae20562017-01-16 20:41:20 +090012214#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012215
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012216/* externally visible for str.strip(unicode) */
12217PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012218_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012219{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012220 void *data;
12221 int kind;
12222 Py_ssize_t i, j, len;
12223 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012224 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012225
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12227 return NULL;
12228
12229 kind = PyUnicode_KIND(self);
12230 data = PyUnicode_DATA(self);
12231 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012232 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012233 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12234 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012235 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012236
Benjamin Peterson14339b62009-01-31 16:36:08 +000012237 i = 0;
12238 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012239 while (i < len) {
12240 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12241 if (!BLOOM(sepmask, ch))
12242 break;
12243 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12244 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012245 i++;
12246 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012247 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012248
Benjamin Peterson14339b62009-01-31 16:36:08 +000012249 j = len;
12250 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012251 j--;
12252 while (j >= i) {
12253 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12254 if (!BLOOM(sepmask, ch))
12255 break;
12256 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12257 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012258 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012259 }
12260
Benjamin Peterson29060642009-01-31 22:14:21 +000012261 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012262 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012263
Victor Stinner7931d9a2011-11-04 00:22:48 +010012264 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265}
12266
12267PyObject*
12268PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12269{
12270 unsigned char *data;
12271 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012272 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012273
Victor Stinnerde636f32011-10-01 03:55:54 +020012274 if (PyUnicode_READY(self) == -1)
12275 return NULL;
12276
Victor Stinner684d5fd2012-05-03 02:32:34 +020012277 length = PyUnicode_GET_LENGTH(self);
12278 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012279
Victor Stinner684d5fd2012-05-03 02:32:34 +020012280 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012281 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012282
Victor Stinnerde636f32011-10-01 03:55:54 +020012283 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012284 PyErr_SetString(PyExc_IndexError, "string index out of range");
12285 return NULL;
12286 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012287 if (start >= length || end < start)
12288 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012289
Victor Stinner684d5fd2012-05-03 02:32:34 +020012290 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012291 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012292 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012293 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012294 }
12295 else {
12296 kind = PyUnicode_KIND(self);
12297 data = PyUnicode_1BYTE_DATA(self);
12298 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012299 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012300 length);
12301 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303
12304static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012305do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012307 Py_ssize_t len, i, j;
12308
12309 if (PyUnicode_READY(self) == -1)
12310 return NULL;
12311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012313
Victor Stinnercc7af722013-04-09 22:39:24 +020012314 if (PyUnicode_IS_ASCII(self)) {
12315 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12316
12317 i = 0;
12318 if (striptype != RIGHTSTRIP) {
12319 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012320 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012321 if (!_Py_ascii_whitespace[ch])
12322 break;
12323 i++;
12324 }
12325 }
12326
12327 j = len;
12328 if (striptype != LEFTSTRIP) {
12329 j--;
12330 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012331 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012332 if (!_Py_ascii_whitespace[ch])
12333 break;
12334 j--;
12335 }
12336 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012337 }
12338 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012339 else {
12340 int kind = PyUnicode_KIND(self);
12341 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012342
Victor Stinnercc7af722013-04-09 22:39:24 +020012343 i = 0;
12344 if (striptype != RIGHTSTRIP) {
12345 while (i < len) {
12346 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12347 if (!Py_UNICODE_ISSPACE(ch))
12348 break;
12349 i++;
12350 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012351 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012352
12353 j = len;
12354 if (striptype != LEFTSTRIP) {
12355 j--;
12356 while (j >= i) {
12357 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12358 if (!Py_UNICODE_ISSPACE(ch))
12359 break;
12360 j--;
12361 }
12362 j++;
12363 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012364 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012365
Victor Stinner7931d9a2011-11-04 00:22:48 +010012366 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012367}
12368
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012369
12370static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012371do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012372{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012373 if (sep != NULL && sep != Py_None) {
12374 if (PyUnicode_Check(sep))
12375 return _PyUnicode_XStrip(self, striptype, sep);
12376 else {
12377 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012378 "%s arg must be None or str",
12379 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012380 return NULL;
12381 }
12382 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012383
Benjamin Peterson14339b62009-01-31 16:36:08 +000012384 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012385}
12386
12387
INADA Naoki3ae20562017-01-16 20:41:20 +090012388/*[clinic input]
12389str.strip as unicode_strip
12390
12391 chars: object = None
12392 /
12393
Victor Stinner0c4a8282017-01-17 02:21:47 +010012394Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012395
12396If chars is given and not None, remove characters in chars instead.
12397[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012398
12399static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012400unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012401/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012402{
INADA Naoki3ae20562017-01-16 20:41:20 +090012403 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012404}
12405
12406
INADA Naoki3ae20562017-01-16 20:41:20 +090012407/*[clinic input]
12408str.lstrip as unicode_lstrip
12409
12410 chars: object = NULL
12411 /
12412
12413Return a copy of the string with leading whitespace removed.
12414
12415If chars is given and not None, remove characters in chars instead.
12416[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012417
12418static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012419unicode_lstrip_impl(PyObject *self, PyObject *chars)
12420/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012421{
INADA Naoki3ae20562017-01-16 20:41:20 +090012422 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012423}
12424
12425
INADA Naoki3ae20562017-01-16 20:41:20 +090012426/*[clinic input]
12427str.rstrip as unicode_rstrip
12428
12429 chars: object = NULL
12430 /
12431
12432Return a copy of the string with trailing whitespace removed.
12433
12434If chars is given and not None, remove characters in chars instead.
12435[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012436
12437static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012438unicode_rstrip_impl(PyObject *self, PyObject *chars)
12439/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012440{
INADA Naoki3ae20562017-01-16 20:41:20 +090012441 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012442}
12443
12444
Guido van Rossumd57fd912000-03-10 22:53:23 +000012445static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012446unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012448 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012449 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012450
Serhiy Storchaka05997252013-01-26 12:14:02 +020012451 if (len < 1)
12452 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012453
Victor Stinnerc4b49542011-12-11 22:44:26 +010012454 /* no repeat, return original string */
12455 if (len == 1)
12456 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012457
Benjamin Petersonbac79492012-01-14 13:34:47 -050012458 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012459 return NULL;
12460
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012461 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012462 PyErr_SetString(PyExc_OverflowError,
12463 "repeated string is too long");
12464 return NULL;
12465 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012466 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012467
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012468 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469 if (!u)
12470 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012471 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012472
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 if (PyUnicode_GET_LENGTH(str) == 1) {
12474 const int kind = PyUnicode_KIND(str);
12475 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012476 if (kind == PyUnicode_1BYTE_KIND) {
12477 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012478 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012479 }
12480 else if (kind == PyUnicode_2BYTE_KIND) {
12481 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012482 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012483 ucs2[n] = fill_char;
12484 } else {
12485 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12486 assert(kind == PyUnicode_4BYTE_KIND);
12487 for (n = 0; n < len; ++n)
12488 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012489 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012490 }
12491 else {
12492 /* number of characters copied this far */
12493 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012494 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012495 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012496 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012498 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012499 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012500 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012501 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012502 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503 }
12504
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012505 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012506 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012507}
12508
Alexander Belopolsky40018472011-02-26 01:02:56 +000012509PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012510PyUnicode_Replace(PyObject *str,
12511 PyObject *substr,
12512 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012513 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012514{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012515 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12516 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012517 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012518 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012519}
12520
INADA Naoki3ae20562017-01-16 20:41:20 +090012521/*[clinic input]
12522str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012523
INADA Naoki3ae20562017-01-16 20:41:20 +090012524 old: unicode
12525 new: unicode
12526 count: Py_ssize_t = -1
12527 Maximum number of occurrences to replace.
12528 -1 (the default value) means replace all occurrences.
12529 /
12530
12531Return a copy with all occurrences of substring old replaced by new.
12532
12533If the optional argument count is given, only the first count occurrences are
12534replaced.
12535[clinic start generated code]*/
12536
12537static PyObject *
12538unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12539 Py_ssize_t count)
12540/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012541{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012542 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012543 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012544 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545}
12546
Alexander Belopolsky40018472011-02-26 01:02:56 +000012547static PyObject *
12548unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012550 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012551 Py_ssize_t isize;
12552 Py_ssize_t osize, squote, dquote, i, o;
12553 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012554 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012557 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012558 return NULL;
12559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 isize = PyUnicode_GET_LENGTH(unicode);
12561 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012562
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 /* Compute length of output, quote characters, and
12564 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012565 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012566 max = 127;
12567 squote = dquote = 0;
12568 ikind = PyUnicode_KIND(unicode);
12569 for (i = 0; i < isize; i++) {
12570 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012571 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012572 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012573 case '\'': squote++; break;
12574 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012576 incr = 2;
12577 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 default:
12579 /* Fast-path ASCII */
12580 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012581 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012582 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012583 ;
12584 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012586 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012587 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012589 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012591 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012593 if (osize > PY_SSIZE_T_MAX - incr) {
12594 PyErr_SetString(PyExc_OverflowError,
12595 "string is too long to generate repr");
12596 return NULL;
12597 }
12598 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012599 }
12600
12601 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012602 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012604 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012605 if (dquote)
12606 /* Both squote and dquote present. Use squote,
12607 and escape them */
12608 osize += squote;
12609 else
12610 quote = '"';
12611 }
Victor Stinner55c08782013-04-14 18:45:39 +020012612 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613
12614 repr = PyUnicode_New(osize, max);
12615 if (repr == NULL)
12616 return NULL;
12617 okind = PyUnicode_KIND(repr);
12618 odata = PyUnicode_DATA(repr);
12619
12620 PyUnicode_WRITE(okind, odata, 0, quote);
12621 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012622 if (unchanged) {
12623 _PyUnicode_FastCopyCharacters(repr, 1,
12624 unicode, 0,
12625 isize);
12626 }
12627 else {
12628 for (i = 0, o = 1; i < isize; i++) {
12629 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012630
Victor Stinner55c08782013-04-14 18:45:39 +020012631 /* Escape quotes and backslashes */
12632 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012633 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012634 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012635 continue;
12636 }
12637
12638 /* Map special whitespace to '\t', \n', '\r' */
12639 if (ch == '\t') {
12640 PyUnicode_WRITE(okind, odata, o++, '\\');
12641 PyUnicode_WRITE(okind, odata, o++, 't');
12642 }
12643 else if (ch == '\n') {
12644 PyUnicode_WRITE(okind, odata, o++, '\\');
12645 PyUnicode_WRITE(okind, odata, o++, 'n');
12646 }
12647 else if (ch == '\r') {
12648 PyUnicode_WRITE(okind, odata, o++, '\\');
12649 PyUnicode_WRITE(okind, odata, o++, 'r');
12650 }
12651
12652 /* Map non-printable US ASCII to '\xhh' */
12653 else if (ch < ' ' || ch == 0x7F) {
12654 PyUnicode_WRITE(okind, odata, o++, '\\');
12655 PyUnicode_WRITE(okind, odata, o++, 'x');
12656 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12657 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12658 }
12659
12660 /* Copy ASCII characters as-is */
12661 else if (ch < 0x7F) {
12662 PyUnicode_WRITE(okind, odata, o++, ch);
12663 }
12664
12665 /* Non-ASCII characters */
12666 else {
12667 /* Map Unicode whitespace and control characters
12668 (categories Z* and C* except ASCII space)
12669 */
12670 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12671 PyUnicode_WRITE(okind, odata, o++, '\\');
12672 /* Map 8-bit characters to '\xhh' */
12673 if (ch <= 0xff) {
12674 PyUnicode_WRITE(okind, odata, o++, 'x');
12675 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12676 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12677 }
12678 /* Map 16-bit characters to '\uxxxx' */
12679 else if (ch <= 0xffff) {
12680 PyUnicode_WRITE(okind, odata, o++, 'u');
12681 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12682 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12683 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12684 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12685 }
12686 /* Map 21-bit characters to '\U00xxxxxx' */
12687 else {
12688 PyUnicode_WRITE(okind, odata, o++, 'U');
12689 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12690 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12691 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12692 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12693 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12694 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12695 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12696 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12697 }
12698 }
12699 /* Copy characters as-is */
12700 else {
12701 PyUnicode_WRITE(okind, odata, o++, ch);
12702 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012703 }
12704 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012705 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012707 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012708 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709}
12710
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012711PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012712 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713\n\
12714Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012715such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716arguments start and end are interpreted as in slice notation.\n\
12717\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012718Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719
12720static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012721unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012723 /* initialize variables to prevent gcc warning */
12724 PyObject *substring = NULL;
12725 Py_ssize_t start = 0;
12726 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012727 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012728
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012729 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012730 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012732 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012733 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012734
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012735 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012736
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012737 if (result == -2)
12738 return NULL;
12739
Christian Heimes217cfd12007-12-02 14:31:20 +000012740 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741}
12742
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012743PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012744 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012746Return the highest index in S where substring sub is found,\n\
12747such that sub is contained within S[start:end]. Optional\n\
12748arguments start and end are interpreted as in slice notation.\n\
12749\n\
12750Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012751
12752static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012753unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012755 /* initialize variables to prevent gcc warning */
12756 PyObject *substring = NULL;
12757 Py_ssize_t start = 0;
12758 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012759 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012761 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012762 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012764 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012766
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012767 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012768
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012769 if (result == -2)
12770 return NULL;
12771
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772 if (result < 0) {
12773 PyErr_SetString(PyExc_ValueError, "substring not found");
12774 return NULL;
12775 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012776
Christian Heimes217cfd12007-12-02 14:31:20 +000012777 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778}
12779
INADA Naoki3ae20562017-01-16 20:41:20 +090012780/*[clinic input]
12781str.rjust as unicode_rjust
12782
12783 width: Py_ssize_t
12784 fillchar: Py_UCS4 = ' '
12785 /
12786
12787Return a right-justified string of length width.
12788
12789Padding is done using the specified fill character (default is a space).
12790[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791
12792static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012793unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12794/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012796 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797 return NULL;
12798
Victor Stinnerc4b49542011-12-11 22:44:26 +010012799 if (PyUnicode_GET_LENGTH(self) >= width)
12800 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801
Victor Stinnerc4b49542011-12-11 22:44:26 +010012802 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803}
12804
Alexander Belopolsky40018472011-02-26 01:02:56 +000012805PyObject *
12806PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012808 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012809 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012811 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012812}
12813
INADA Naoki3ae20562017-01-16 20:41:20 +090012814/*[clinic input]
12815str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816
INADA Naoki3ae20562017-01-16 20:41:20 +090012817 sep: object = None
12818 The delimiter according which to split the string.
12819 None (the default value) means split according to any whitespace,
12820 and discard empty strings from the result.
12821 maxsplit: Py_ssize_t = -1
12822 Maximum number of splits to do.
12823 -1 (the default value) means no limit.
12824
12825Return a list of the words in the string, using sep as the delimiter string.
12826[clinic start generated code]*/
12827
12828static PyObject *
12829unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12830/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831{
INADA Naoki3ae20562017-01-16 20:41:20 +090012832 if (sep == Py_None)
12833 return split(self, NULL, maxsplit);
12834 if (PyUnicode_Check(sep))
12835 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012836
Victor Stinner998b8062018-09-12 00:23:25 +020012837 PyErr_Format(PyExc_TypeError,
12838 "must be str or None, not %.100s",
12839 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012840 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841}
12842
Thomas Wouters477c8d52006-05-27 19:21:47 +000012843PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012844PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012845{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012846 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012847 int kind1, kind2;
12848 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012849 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012850
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012851 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012852 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012853
Victor Stinner14f8f022011-10-05 20:58:25 +020012854 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012855 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012856 len1 = PyUnicode_GET_LENGTH(str_obj);
12857 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012858 if (kind1 < kind2 || len1 < len2) {
12859 _Py_INCREF_UNICODE_EMPTY();
12860 if (!unicode_empty)
12861 out = NULL;
12862 else {
12863 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12864 Py_DECREF(unicode_empty);
12865 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012866 return out;
12867 }
12868 buf1 = PyUnicode_DATA(str_obj);
12869 buf2 = PyUnicode_DATA(sep_obj);
12870 if (kind2 != kind1) {
12871 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12872 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012873 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012874 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012875
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012876 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012877 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012878 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12879 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12880 else
12881 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012882 break;
12883 case PyUnicode_2BYTE_KIND:
12884 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12885 break;
12886 case PyUnicode_4BYTE_KIND:
12887 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12888 break;
12889 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012890 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012891 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012892
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012893 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012894 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012895
12896 return out;
12897}
12898
12899
12900PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012901PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012902{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012903 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012904 int kind1, kind2;
12905 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012906 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012907
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012908 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012909 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012910
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012911 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012912 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012913 len1 = PyUnicode_GET_LENGTH(str_obj);
12914 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012915 if (kind1 < kind2 || len1 < len2) {
12916 _Py_INCREF_UNICODE_EMPTY();
12917 if (!unicode_empty)
12918 out = NULL;
12919 else {
12920 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12921 Py_DECREF(unicode_empty);
12922 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012923 return out;
12924 }
12925 buf1 = PyUnicode_DATA(str_obj);
12926 buf2 = PyUnicode_DATA(sep_obj);
12927 if (kind2 != kind1) {
12928 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12929 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012930 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012931 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012932
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012933 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012934 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012935 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12936 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12937 else
12938 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012939 break;
12940 case PyUnicode_2BYTE_KIND:
12941 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12942 break;
12943 case PyUnicode_4BYTE_KIND:
12944 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12945 break;
12946 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012947 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012948 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012949
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012950 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012951 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012952
12953 return out;
12954}
12955
INADA Naoki3ae20562017-01-16 20:41:20 +090012956/*[clinic input]
12957str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012958
INADA Naoki3ae20562017-01-16 20:41:20 +090012959 sep: object
12960 /
12961
12962Partition the string into three parts using the given separator.
12963
12964This will search for the separator in the string. If the separator is found,
12965returns a 3-tuple containing the part before the separator, the separator
12966itself, and the part after it.
12967
12968If the separator is not found, returns a 3-tuple containing the original string
12969and two empty strings.
12970[clinic start generated code]*/
12971
12972static PyObject *
12973unicode_partition(PyObject *self, PyObject *sep)
12974/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012975{
INADA Naoki3ae20562017-01-16 20:41:20 +090012976 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012977}
12978
INADA Naoki3ae20562017-01-16 20:41:20 +090012979/*[clinic input]
12980str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012981
INADA Naoki3ae20562017-01-16 20:41:20 +090012982Partition the string into three parts using the given separator.
12983
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012984This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012985the separator is found, returns a 3-tuple containing the part before the
12986separator, the separator itself, and the part after it.
12987
12988If the separator is not found, returns a 3-tuple containing two empty strings
12989and the original string.
12990[clinic start generated code]*/
12991
12992static PyObject *
12993unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012994/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012995{
INADA Naoki3ae20562017-01-16 20:41:20 +090012996 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012997}
12998
Alexander Belopolsky40018472011-02-26 01:02:56 +000012999PyObject *
13000PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013001{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013002 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013003 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013004
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013005 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013006}
13007
INADA Naoki3ae20562017-01-16 20:41:20 +090013008/*[clinic input]
13009str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013010
INADA Naoki3ae20562017-01-16 20:41:20 +090013011Return a list of the words in the string, using sep as the delimiter string.
13012
13013Splits are done starting at the end of the string and working to the front.
13014[clinic start generated code]*/
13015
13016static PyObject *
13017unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13018/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013019{
INADA Naoki3ae20562017-01-16 20:41:20 +090013020 if (sep == Py_None)
13021 return rsplit(self, NULL, maxsplit);
13022 if (PyUnicode_Check(sep))
13023 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013024
Victor Stinner998b8062018-09-12 00:23:25 +020013025 PyErr_Format(PyExc_TypeError,
13026 "must be str or None, not %.100s",
13027 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013028 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013029}
13030
INADA Naoki3ae20562017-01-16 20:41:20 +090013031/*[clinic input]
13032str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013033
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013034 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013035
13036Return a list of the lines in the string, breaking at line boundaries.
13037
13038Line breaks are not included in the resulting list unless keepends is given and
13039true.
13040[clinic start generated code]*/
13041
13042static PyObject *
13043unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013044/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013045{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013046 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013047}
13048
13049static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013050PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013051{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013052 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013053}
13054
INADA Naoki3ae20562017-01-16 20:41:20 +090013055/*[clinic input]
13056str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057
INADA Naoki3ae20562017-01-16 20:41:20 +090013058Convert uppercase characters to lowercase and lowercase characters to uppercase.
13059[clinic start generated code]*/
13060
13061static PyObject *
13062unicode_swapcase_impl(PyObject *self)
13063/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013064{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013065 if (PyUnicode_READY(self) == -1)
13066 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013067 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013068}
13069
Larry Hastings61272b72014-01-07 12:41:53 -080013070/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013071
Larry Hastings31826802013-10-19 00:09:25 -070013072@staticmethod
13073str.maketrans as unicode_maketrans
13074
13075 x: object
13076
13077 y: unicode=NULL
13078
13079 z: unicode=NULL
13080
13081 /
13082
13083Return a translation table usable for str.translate().
13084
13085If there is only one argument, it must be a dictionary mapping Unicode
13086ordinals (integers) or characters to Unicode ordinals, strings or None.
13087Character keys will be then converted to ordinals.
13088If there are two arguments, they must be strings of equal length, and
13089in the resulting dictionary, each character in x will be mapped to the
13090character at the same position in y. If there is a third argument, it
13091must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013092[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013093
Larry Hastings31826802013-10-19 00:09:25 -070013094static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013095unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013096/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013097{
Georg Brandlceee0772007-11-27 23:48:05 +000013098 PyObject *new = NULL, *key, *value;
13099 Py_ssize_t i = 0;
13100 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013101
Georg Brandlceee0772007-11-27 23:48:05 +000013102 new = PyDict_New();
13103 if (!new)
13104 return NULL;
13105 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013106 int x_kind, y_kind, z_kind;
13107 void *x_data, *y_data, *z_data;
13108
Georg Brandlceee0772007-11-27 23:48:05 +000013109 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013110 if (!PyUnicode_Check(x)) {
13111 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13112 "be a string if there is a second argument");
13113 goto err;
13114 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013115 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013116 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13117 "arguments must have equal length");
13118 goto err;
13119 }
13120 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013121 x_kind = PyUnicode_KIND(x);
13122 y_kind = PyUnicode_KIND(y);
13123 x_data = PyUnicode_DATA(x);
13124 y_data = PyUnicode_DATA(y);
13125 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13126 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013127 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013128 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013129 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013130 if (!value) {
13131 Py_DECREF(key);
13132 goto err;
13133 }
Georg Brandlceee0772007-11-27 23:48:05 +000013134 res = PyDict_SetItem(new, key, value);
13135 Py_DECREF(key);
13136 Py_DECREF(value);
13137 if (res < 0)
13138 goto err;
13139 }
13140 /* create entries for deleting chars in z */
13141 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013142 z_kind = PyUnicode_KIND(z);
13143 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013144 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013146 if (!key)
13147 goto err;
13148 res = PyDict_SetItem(new, key, Py_None);
13149 Py_DECREF(key);
13150 if (res < 0)
13151 goto err;
13152 }
13153 }
13154 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013155 int kind;
13156 void *data;
13157
Georg Brandlceee0772007-11-27 23:48:05 +000013158 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013159 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013160 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13161 "to maketrans it must be a dict");
13162 goto err;
13163 }
13164 /* copy entries into the new dict, converting string keys to int keys */
13165 while (PyDict_Next(x, &i, &key, &value)) {
13166 if (PyUnicode_Check(key)) {
13167 /* convert string keys to integer keys */
13168 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013169 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013170 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13171 "table must be of length 1");
13172 goto err;
13173 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013174 kind = PyUnicode_KIND(key);
13175 data = PyUnicode_DATA(key);
13176 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013177 if (!newkey)
13178 goto err;
13179 res = PyDict_SetItem(new, newkey, value);
13180 Py_DECREF(newkey);
13181 if (res < 0)
13182 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013183 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013184 /* just keep integer keys */
13185 if (PyDict_SetItem(new, key, value) < 0)
13186 goto err;
13187 } else {
13188 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13189 "be strings or integers");
13190 goto err;
13191 }
13192 }
13193 }
13194 return new;
13195 err:
13196 Py_DECREF(new);
13197 return NULL;
13198}
13199
INADA Naoki3ae20562017-01-16 20:41:20 +090013200/*[clinic input]
13201str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013202
INADA Naoki3ae20562017-01-16 20:41:20 +090013203 table: object
13204 Translation table, which must be a mapping of Unicode ordinals to
13205 Unicode ordinals, strings, or None.
13206 /
13207
13208Replace each character in the string using the given translation table.
13209
13210The table must implement lookup/indexing via __getitem__, for instance a
13211dictionary or list. If this operation raises LookupError, the character is
13212left untouched. Characters mapped to None are deleted.
13213[clinic start generated code]*/
13214
13215static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013216unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013217/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013218{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013219 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220}
13221
INADA Naoki3ae20562017-01-16 20:41:20 +090013222/*[clinic input]
13223str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013224
INADA Naoki3ae20562017-01-16 20:41:20 +090013225Return a copy of the string converted to uppercase.
13226[clinic start generated code]*/
13227
13228static PyObject *
13229unicode_upper_impl(PyObject *self)
13230/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013232 if (PyUnicode_READY(self) == -1)
13233 return NULL;
13234 if (PyUnicode_IS_ASCII(self))
13235 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013236 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237}
13238
INADA Naoki3ae20562017-01-16 20:41:20 +090013239/*[clinic input]
13240str.zfill as unicode_zfill
13241
13242 width: Py_ssize_t
13243 /
13244
13245Pad a numeric string with zeros on the left, to fill a field of the given width.
13246
13247The string is never truncated.
13248[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013249
13250static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013251unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013252/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013253{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013254 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013255 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013256 int kind;
13257 void *data;
13258 Py_UCS4 chr;
13259
Benjamin Petersonbac79492012-01-14 13:34:47 -050013260 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013261 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013262
Victor Stinnerc4b49542011-12-11 22:44:26 +010013263 if (PyUnicode_GET_LENGTH(self) >= width)
13264 return unicode_result_unchanged(self);
13265
13266 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267
13268 u = pad(self, fill, 0, '0');
13269
Walter Dörwald068325e2002-04-15 13:36:47 +000013270 if (u == NULL)
13271 return NULL;
13272
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013273 kind = PyUnicode_KIND(u);
13274 data = PyUnicode_DATA(u);
13275 chr = PyUnicode_READ(kind, data, fill);
13276
13277 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013278 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013279 PyUnicode_WRITE(kind, data, 0, chr);
13280 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281 }
13282
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013283 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013284 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013285}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013286
13287#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013288static PyObject *
13289unicode__decimal2ascii(PyObject *self)
13290{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013292}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013293#endif
13294
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013295PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013296 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013297\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013298Return True if S starts with the specified prefix, False otherwise.\n\
13299With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013300With optional end, stop comparing S at that position.\n\
13301prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302
13303static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013304unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013305 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013306{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013307 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013308 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013309 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013310 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013311 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013312
Jesus Ceaac451502011-04-20 17:09:23 +020013313 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013314 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013315 if (PyTuple_Check(subobj)) {
13316 Py_ssize_t i;
13317 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013318 substring = PyTuple_GET_ITEM(subobj, i);
13319 if (!PyUnicode_Check(substring)) {
13320 PyErr_Format(PyExc_TypeError,
13321 "tuple for startswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013322 "not %.100s",
13323 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013324 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013325 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013326 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013327 if (result == -1)
13328 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013329 if (result) {
13330 Py_RETURN_TRUE;
13331 }
13332 }
13333 /* nothing matched */
13334 Py_RETURN_FALSE;
13335 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013336 if (!PyUnicode_Check(subobj)) {
13337 PyErr_Format(PyExc_TypeError,
13338 "startswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013339 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013340 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013341 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013342 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013343 if (result == -1)
13344 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013345 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013346}
13347
13348
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013349PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013350 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013351\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013352Return True if S ends with the specified suffix, False otherwise.\n\
13353With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013354With optional end, stop comparing S at that position.\n\
13355suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013356
13357static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013358unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013359 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013360{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013361 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013362 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013363 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013364 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013365 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013366
Jesus Ceaac451502011-04-20 17:09:23 +020013367 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013368 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013369 if (PyTuple_Check(subobj)) {
13370 Py_ssize_t i;
13371 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013372 substring = PyTuple_GET_ITEM(subobj, i);
13373 if (!PyUnicode_Check(substring)) {
13374 PyErr_Format(PyExc_TypeError,
13375 "tuple for endswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013376 "not %.100s",
13377 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013378 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013379 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013380 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013381 if (result == -1)
13382 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013383 if (result) {
13384 Py_RETURN_TRUE;
13385 }
13386 }
13387 Py_RETURN_FALSE;
13388 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013389 if (!PyUnicode_Check(subobj)) {
13390 PyErr_Format(PyExc_TypeError,
13391 "endswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013392 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013393 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013394 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013395 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013396 if (result == -1)
13397 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013398 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013399}
13400
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013401static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013402_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013403{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013404 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13405 writer->data = PyUnicode_DATA(writer->buffer);
13406
13407 if (!writer->readonly) {
13408 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013409 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013410 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013411 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013412 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13413 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13414 writer->kind = PyUnicode_WCHAR_KIND;
13415 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13416
Victor Stinner8f674cc2013-04-17 23:02:17 +020013417 /* Copy-on-write mode: set buffer size to 0 so
13418 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13419 * next write. */
13420 writer->size = 0;
13421 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013422}
13423
Victor Stinnerd3f08822012-05-29 12:57:52 +020013424void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013425_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013426{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013427 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013428
13429 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013430 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013431
13432 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13433 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13434 writer->kind = PyUnicode_WCHAR_KIND;
13435 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013436}
13437
Victor Stinnerd3f08822012-05-29 12:57:52 +020013438int
13439_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13440 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013441{
13442 Py_ssize_t newlen;
13443 PyObject *newbuffer;
13444
Victor Stinner2740e462016-09-06 16:58:36 -070013445 assert(maxchar <= MAX_UNICODE);
13446
Victor Stinnerca9381e2015-09-22 00:58:32 +020013447 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013448 assert((maxchar > writer->maxchar && length >= 0)
13449 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013450
Victor Stinner202fdca2012-05-07 12:47:02 +020013451 if (length > PY_SSIZE_T_MAX - writer->pos) {
13452 PyErr_NoMemory();
13453 return -1;
13454 }
13455 newlen = writer->pos + length;
13456
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013457 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013458
Victor Stinnerd3f08822012-05-29 12:57:52 +020013459 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013460 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013461 if (writer->overallocate
13462 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13463 /* overallocate to limit the number of realloc() */
13464 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013465 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013466 if (newlen < writer->min_length)
13467 newlen = writer->min_length;
13468
Victor Stinnerd3f08822012-05-29 12:57:52 +020013469 writer->buffer = PyUnicode_New(newlen, maxchar);
13470 if (writer->buffer == NULL)
13471 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013472 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013473 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013474 if (writer->overallocate
13475 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13476 /* overallocate to limit the number of realloc() */
13477 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013478 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013479 if (newlen < writer->min_length)
13480 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013481
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013482 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013483 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013484 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013485 newbuffer = PyUnicode_New(newlen, maxchar);
13486 if (newbuffer == NULL)
13487 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013488 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13489 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013490 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013491 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013492 }
13493 else {
13494 newbuffer = resize_compact(writer->buffer, newlen);
13495 if (newbuffer == NULL)
13496 return -1;
13497 }
13498 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013499 }
13500 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013501 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013502 newbuffer = PyUnicode_New(writer->size, maxchar);
13503 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013504 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013505 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13506 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013507 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013508 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013509 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013510 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013511
13512#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013513}
13514
Victor Stinnerca9381e2015-09-22 00:58:32 +020013515int
13516_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13517 enum PyUnicode_Kind kind)
13518{
13519 Py_UCS4 maxchar;
13520
13521 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13522 assert(writer->kind < kind);
13523
13524 switch (kind)
13525 {
13526 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13527 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13528 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13529 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013530 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013531 }
13532
13533 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13534}
13535
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013536static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013537_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013538{
Victor Stinner2740e462016-09-06 16:58:36 -070013539 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013540 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13541 return -1;
13542 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13543 writer->pos++;
13544 return 0;
13545}
13546
13547int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013548_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13549{
13550 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13551}
13552
13553int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013554_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13555{
13556 Py_UCS4 maxchar;
13557 Py_ssize_t len;
13558
13559 if (PyUnicode_READY(str) == -1)
13560 return -1;
13561 len = PyUnicode_GET_LENGTH(str);
13562 if (len == 0)
13563 return 0;
13564 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13565 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013566 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013567 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013568 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013569 Py_INCREF(str);
13570 writer->buffer = str;
13571 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013572 writer->pos += len;
13573 return 0;
13574 }
13575 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13576 return -1;
13577 }
13578 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13579 str, 0, len);
13580 writer->pos += len;
13581 return 0;
13582}
13583
Victor Stinnere215d962012-10-06 23:03:36 +020013584int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013585_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13586 Py_ssize_t start, Py_ssize_t end)
13587{
13588 Py_UCS4 maxchar;
13589 Py_ssize_t len;
13590
13591 if (PyUnicode_READY(str) == -1)
13592 return -1;
13593
13594 assert(0 <= start);
13595 assert(end <= PyUnicode_GET_LENGTH(str));
13596 assert(start <= end);
13597
13598 if (end == 0)
13599 return 0;
13600
13601 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13602 return _PyUnicodeWriter_WriteStr(writer, str);
13603
13604 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13605 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13606 else
13607 maxchar = writer->maxchar;
13608 len = end - start;
13609
13610 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13611 return -1;
13612
13613 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13614 str, start, len);
13615 writer->pos += len;
13616 return 0;
13617}
13618
13619int
Victor Stinner4a587072013-11-19 12:54:53 +010013620_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13621 const char *ascii, Py_ssize_t len)
13622{
13623 if (len == -1)
13624 len = strlen(ascii);
13625
13626 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13627
13628 if (writer->buffer == NULL && !writer->overallocate) {
13629 PyObject *str;
13630
13631 str = _PyUnicode_FromASCII(ascii, len);
13632 if (str == NULL)
13633 return -1;
13634
13635 writer->readonly = 1;
13636 writer->buffer = str;
13637 _PyUnicodeWriter_Update(writer);
13638 writer->pos += len;
13639 return 0;
13640 }
13641
13642 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13643 return -1;
13644
13645 switch (writer->kind)
13646 {
13647 case PyUnicode_1BYTE_KIND:
13648 {
13649 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13650 Py_UCS1 *data = writer->data;
13651
Christian Heimesf051e432016-09-13 20:22:02 +020013652 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013653 break;
13654 }
13655 case PyUnicode_2BYTE_KIND:
13656 {
13657 _PyUnicode_CONVERT_BYTES(
13658 Py_UCS1, Py_UCS2,
13659 ascii, ascii + len,
13660 (Py_UCS2 *)writer->data + writer->pos);
13661 break;
13662 }
13663 case PyUnicode_4BYTE_KIND:
13664 {
13665 _PyUnicode_CONVERT_BYTES(
13666 Py_UCS1, Py_UCS4,
13667 ascii, ascii + len,
13668 (Py_UCS4 *)writer->data + writer->pos);
13669 break;
13670 }
13671 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013672 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013673 }
13674
13675 writer->pos += len;
13676 return 0;
13677}
13678
13679int
13680_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13681 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013682{
13683 Py_UCS4 maxchar;
13684
13685 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13686 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13687 return -1;
13688 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13689 writer->pos += len;
13690 return 0;
13691}
13692
Victor Stinnerd3f08822012-05-29 12:57:52 +020013693PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013694_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013695{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013696 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013697
Victor Stinnerd3f08822012-05-29 12:57:52 +020013698 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013699 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013700 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013701 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013702
13703 str = writer->buffer;
13704 writer->buffer = NULL;
13705
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013706 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013707 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13708 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013709 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013710
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013711 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13712 PyObject *str2;
13713 str2 = resize_compact(str, writer->pos);
13714 if (str2 == NULL) {
13715 Py_DECREF(str);
13716 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013717 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013718 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013719 }
13720
Victor Stinner15a0bd32013-07-08 22:29:55 +020013721 assert(_PyUnicode_CheckConsistency(str, 1));
13722 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013723}
13724
Victor Stinnerd3f08822012-05-29 12:57:52 +020013725void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013726_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013727{
13728 Py_CLEAR(writer->buffer);
13729}
13730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013731#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013732
13733PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013734 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013735\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013736Return a formatted version of S, using substitutions from args and kwargs.\n\
13737The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013738
Eric Smith27bbca62010-11-04 17:06:58 +000013739PyDoc_STRVAR(format_map__doc__,
13740 "S.format_map(mapping) -> str\n\
13741\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013742Return a formatted version of S, using substitutions from mapping.\n\
13743The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013744
INADA Naoki3ae20562017-01-16 20:41:20 +090013745/*[clinic input]
13746str.__format__ as unicode___format__
13747
13748 format_spec: unicode
13749 /
13750
13751Return a formatted version of the string as described by format_spec.
13752[clinic start generated code]*/
13753
Eric Smith4a7d76d2008-05-30 18:10:19 +000013754static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013755unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013756/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013757{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013758 _PyUnicodeWriter writer;
13759 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013760
Victor Stinnerd3f08822012-05-29 12:57:52 +020013761 if (PyUnicode_READY(self) == -1)
13762 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013763 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013764 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13765 self, format_spec, 0,
13766 PyUnicode_GET_LENGTH(format_spec));
13767 if (ret == -1) {
13768 _PyUnicodeWriter_Dealloc(&writer);
13769 return NULL;
13770 }
13771 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013772}
13773
INADA Naoki3ae20562017-01-16 20:41:20 +090013774/*[clinic input]
13775str.__sizeof__ as unicode_sizeof
13776
13777Return the size of the string in memory, in bytes.
13778[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013779
13780static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013781unicode_sizeof_impl(PyObject *self)
13782/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013783{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013784 Py_ssize_t size;
13785
13786 /* If it's a compact object, account for base structure +
13787 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013788 if (PyUnicode_IS_COMPACT_ASCII(self))
13789 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13790 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013791 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013792 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013793 else {
13794 /* If it is a two-block object, account for base object, and
13795 for character block if present. */
13796 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013797 if (_PyUnicode_DATA_ANY(self))
13798 size += (PyUnicode_GET_LENGTH(self) + 1) *
13799 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013800 }
13801 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013802 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013803 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13804 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13805 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13806 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013807
13808 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013809}
13810
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013811static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013812unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013813{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013814 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013815 if (!copy)
13816 return NULL;
13817 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013818}
13819
Guido van Rossumd57fd912000-03-10 22:53:23 +000013820static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013821 UNICODE_ENCODE_METHODDEF
13822 UNICODE_REPLACE_METHODDEF
13823 UNICODE_SPLIT_METHODDEF
13824 UNICODE_RSPLIT_METHODDEF
13825 UNICODE_JOIN_METHODDEF
13826 UNICODE_CAPITALIZE_METHODDEF
13827 UNICODE_CASEFOLD_METHODDEF
13828 UNICODE_TITLE_METHODDEF
13829 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013830 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013831 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013832 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013833 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013834 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013835 UNICODE_LJUST_METHODDEF
13836 UNICODE_LOWER_METHODDEF
13837 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013838 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13839 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013840 UNICODE_RJUST_METHODDEF
13841 UNICODE_RSTRIP_METHODDEF
13842 UNICODE_RPARTITION_METHODDEF
13843 UNICODE_SPLITLINES_METHODDEF
13844 UNICODE_STRIP_METHODDEF
13845 UNICODE_SWAPCASE_METHODDEF
13846 UNICODE_TRANSLATE_METHODDEF
13847 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013848 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13849 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013850 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013851 UNICODE_ISLOWER_METHODDEF
13852 UNICODE_ISUPPER_METHODDEF
13853 UNICODE_ISTITLE_METHODDEF
13854 UNICODE_ISSPACE_METHODDEF
13855 UNICODE_ISDECIMAL_METHODDEF
13856 UNICODE_ISDIGIT_METHODDEF
13857 UNICODE_ISNUMERIC_METHODDEF
13858 UNICODE_ISALPHA_METHODDEF
13859 UNICODE_ISALNUM_METHODDEF
13860 UNICODE_ISIDENTIFIER_METHODDEF
13861 UNICODE_ISPRINTABLE_METHODDEF
13862 UNICODE_ZFILL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013863 {"format", (PyCFunction)(void(*)(void)) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013864 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013865 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013866 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013867 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013868#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013869 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013870 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013871#endif
13872
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013873 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013874 {NULL, NULL}
13875};
13876
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013877static PyObject *
13878unicode_mod(PyObject *v, PyObject *w)
13879{
Brian Curtindfc80e32011-08-10 20:28:54 -050013880 if (!PyUnicode_Check(v))
13881 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013882 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013883}
13884
13885static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013886 0, /*nb_add*/
13887 0, /*nb_subtract*/
13888 0, /*nb_multiply*/
13889 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013890};
13891
Guido van Rossumd57fd912000-03-10 22:53:23 +000013892static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013893 (lenfunc) unicode_length, /* sq_length */
13894 PyUnicode_Concat, /* sq_concat */
13895 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13896 (ssizeargfunc) unicode_getitem, /* sq_item */
13897 0, /* sq_slice */
13898 0, /* sq_ass_item */
13899 0, /* sq_ass_slice */
13900 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013901};
13902
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013903static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013904unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013905{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013906 if (PyUnicode_READY(self) == -1)
13907 return NULL;
13908
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013909 if (PyIndex_Check(item)) {
13910 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013911 if (i == -1 && PyErr_Occurred())
13912 return NULL;
13913 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013914 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013915 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013916 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013917 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013918 PyObject *result;
13919 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013920 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013921 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013922
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013923 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013924 return NULL;
13925 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013926 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13927 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013928
13929 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013930 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013931 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013932 slicelength == PyUnicode_GET_LENGTH(self)) {
13933 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013934 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013935 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013936 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013937 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013938 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013939 src_kind = PyUnicode_KIND(self);
13940 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013941 if (!PyUnicode_IS_ASCII(self)) {
13942 kind_limit = kind_maxchar_limit(src_kind);
13943 max_char = 0;
13944 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13945 ch = PyUnicode_READ(src_kind, src_data, cur);
13946 if (ch > max_char) {
13947 max_char = ch;
13948 if (max_char >= kind_limit)
13949 break;
13950 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013951 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013952 }
Victor Stinner55c99112011-10-13 01:17:06 +020013953 else
13954 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013955 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013956 if (result == NULL)
13957 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013958 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013959 dest_data = PyUnicode_DATA(result);
13960
13961 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013962 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13963 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013964 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013965 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013966 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013967 } else {
13968 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13969 return NULL;
13970 }
13971}
13972
13973static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013974 (lenfunc)unicode_length, /* mp_length */
13975 (binaryfunc)unicode_subscript, /* mp_subscript */
13976 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013977};
13978
Guido van Rossumd57fd912000-03-10 22:53:23 +000013979
Guido van Rossumd57fd912000-03-10 22:53:23 +000013980/* Helpers for PyUnicode_Format() */
13981
Victor Stinnera47082312012-10-04 02:19:54 +020013982struct unicode_formatter_t {
13983 PyObject *args;
13984 int args_owned;
13985 Py_ssize_t arglen, argidx;
13986 PyObject *dict;
13987
13988 enum PyUnicode_Kind fmtkind;
13989 Py_ssize_t fmtcnt, fmtpos;
13990 void *fmtdata;
13991 PyObject *fmtstr;
13992
13993 _PyUnicodeWriter writer;
13994};
13995
13996struct unicode_format_arg_t {
13997 Py_UCS4 ch;
13998 int flags;
13999 Py_ssize_t width;
14000 int prec;
14001 int sign;
14002};
14003
Guido van Rossumd57fd912000-03-10 22:53:23 +000014004static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014005unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014006{
Victor Stinnera47082312012-10-04 02:19:54 +020014007 Py_ssize_t argidx = ctx->argidx;
14008
14009 if (argidx < ctx->arglen) {
14010 ctx->argidx++;
14011 if (ctx->arglen < 0)
14012 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014013 else
Victor Stinnera47082312012-10-04 02:19:54 +020014014 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014015 }
14016 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014017 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014018 return NULL;
14019}
14020
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014021/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014022
Victor Stinnera47082312012-10-04 02:19:54 +020014023/* Format a float into the writer if the writer is not NULL, or into *p_output
14024 otherwise.
14025
14026 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014027static int
Victor Stinnera47082312012-10-04 02:19:54 +020014028formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14029 PyObject **p_output,
14030 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014031{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014032 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014033 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014034 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014035 int prec;
14036 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014037
Guido van Rossumd57fd912000-03-10 22:53:23 +000014038 x = PyFloat_AsDouble(v);
14039 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014040 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014041
Victor Stinnera47082312012-10-04 02:19:54 +020014042 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014043 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014044 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014045
Victor Stinnera47082312012-10-04 02:19:54 +020014046 if (arg->flags & F_ALT)
14047 dtoa_flags = Py_DTSF_ALT;
14048 else
14049 dtoa_flags = 0;
14050 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014051 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014052 return -1;
14053 len = strlen(p);
14054 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014055 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014056 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014057 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014058 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014059 }
14060 else
14061 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014062 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014063 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014064}
14065
Victor Stinnerd0880d52012-04-27 23:40:13 +020014066/* formatlong() emulates the format codes d, u, o, x and X, and
14067 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14068 * Python's regular ints.
14069 * Return value: a new PyUnicodeObject*, or NULL if error.
14070 * The output string is of the form
14071 * "-"? ("0x" | "0X")? digit+
14072 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14073 * set in flags. The case of hex digits will be correct,
14074 * There will be at least prec digits, zero-filled on the left if
14075 * necessary to get that many.
14076 * val object to be converted
14077 * flags bitmask of format flags; only F_ALT is looked at
14078 * prec minimum number of digits; 0-fill on left if needed
14079 * type a character in [duoxX]; u acts the same as d
14080 *
14081 * CAUTION: o, x and X conversions on regular ints can never
14082 * produce a '-' sign, but can for Python's unbounded ints.
14083 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014084PyObject *
14085_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014086{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014087 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014088 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014089 Py_ssize_t i;
14090 int sign; /* 1 if '-', else 0 */
14091 int len; /* number of characters */
14092 Py_ssize_t llen;
14093 int numdigits; /* len == numnondigits + numdigits */
14094 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014095
Victor Stinnerd0880d52012-04-27 23:40:13 +020014096 /* Avoid exceeding SSIZE_T_MAX */
14097 if (prec > INT_MAX-3) {
14098 PyErr_SetString(PyExc_OverflowError,
14099 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014100 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014101 }
14102
14103 assert(PyLong_Check(val));
14104
14105 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014106 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014107 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014108 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014109 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014110 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014111 /* int and int subclasses should print numerically when a numeric */
14112 /* format code is used (see issue18780) */
14113 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014114 break;
14115 case 'o':
14116 numnondigits = 2;
14117 result = PyNumber_ToBase(val, 8);
14118 break;
14119 case 'x':
14120 case 'X':
14121 numnondigits = 2;
14122 result = PyNumber_ToBase(val, 16);
14123 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014124 }
14125 if (!result)
14126 return NULL;
14127
14128 assert(unicode_modifiable(result));
14129 assert(PyUnicode_IS_READY(result));
14130 assert(PyUnicode_IS_ASCII(result));
14131
14132 /* To modify the string in-place, there can only be one reference. */
14133 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014134 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014135 PyErr_BadInternalCall();
14136 return NULL;
14137 }
14138 buf = PyUnicode_DATA(result);
14139 llen = PyUnicode_GET_LENGTH(result);
14140 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014141 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014142 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014143 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014144 return NULL;
14145 }
14146 len = (int)llen;
14147 sign = buf[0] == '-';
14148 numnondigits += sign;
14149 numdigits = len - numnondigits;
14150 assert(numdigits > 0);
14151
14152 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014153 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014154 (type == 'o' || type == 'x' || type == 'X'))) {
14155 assert(buf[sign] == '0');
14156 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14157 buf[sign+1] == 'o');
14158 numnondigits -= 2;
14159 buf += 2;
14160 len -= 2;
14161 if (sign)
14162 buf[0] = '-';
14163 assert(len == numnondigits + numdigits);
14164 assert(numdigits > 0);
14165 }
14166
14167 /* Fill with leading zeroes to meet minimum width. */
14168 if (prec > numdigits) {
14169 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14170 numnondigits + prec);
14171 char *b1;
14172 if (!r1) {
14173 Py_DECREF(result);
14174 return NULL;
14175 }
14176 b1 = PyBytes_AS_STRING(r1);
14177 for (i = 0; i < numnondigits; ++i)
14178 *b1++ = *buf++;
14179 for (i = 0; i < prec - numdigits; i++)
14180 *b1++ = '0';
14181 for (i = 0; i < numdigits; i++)
14182 *b1++ = *buf++;
14183 *b1 = '\0';
14184 Py_DECREF(result);
14185 result = r1;
14186 buf = PyBytes_AS_STRING(result);
14187 len = numnondigits + prec;
14188 }
14189
14190 /* Fix up case for hex conversions. */
14191 if (type == 'X') {
14192 /* Need to convert all lower case letters to upper case.
14193 and need to convert 0x to 0X (and -0x to -0X). */
14194 for (i = 0; i < len; i++)
14195 if (buf[i] >= 'a' && buf[i] <= 'x')
14196 buf[i] -= 'a'-'A';
14197 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014198 if (!PyUnicode_Check(result)
14199 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014200 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014201 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014202 Py_DECREF(result);
14203 result = unicode;
14204 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014205 else if (len != PyUnicode_GET_LENGTH(result)) {
14206 if (PyUnicode_Resize(&result, len) < 0)
14207 Py_CLEAR(result);
14208 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014209 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014210}
14211
Ethan Furmandf3ed242014-01-05 06:50:30 -080014212/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014213 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014214 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014215 * -1 and raise an exception on error */
14216static int
Victor Stinnera47082312012-10-04 02:19:54 +020014217mainformatlong(PyObject *v,
14218 struct unicode_format_arg_t *arg,
14219 PyObject **p_output,
14220 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014221{
14222 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014223 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014224
14225 if (!PyNumber_Check(v))
14226 goto wrongtype;
14227
Ethan Furman9ab74802014-03-21 06:38:46 -070014228 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014229 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014230 if (type == 'o' || type == 'x' || type == 'X') {
14231 iobj = PyNumber_Index(v);
14232 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014233 if (PyErr_ExceptionMatches(PyExc_TypeError))
14234 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014235 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014236 }
14237 }
14238 else {
14239 iobj = PyNumber_Long(v);
14240 if (iobj == NULL ) {
14241 if (PyErr_ExceptionMatches(PyExc_TypeError))
14242 goto wrongtype;
14243 return -1;
14244 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014245 }
14246 assert(PyLong_Check(iobj));
14247 }
14248 else {
14249 iobj = v;
14250 Py_INCREF(iobj);
14251 }
14252
14253 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014254 && arg->width == -1 && arg->prec == -1
14255 && !(arg->flags & (F_SIGN | F_BLANK))
14256 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014257 {
14258 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014259 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014260 int base;
14261
Victor Stinnera47082312012-10-04 02:19:54 +020014262 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014263 {
14264 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014265 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014266 case 'd':
14267 case 'i':
14268 case 'u':
14269 base = 10;
14270 break;
14271 case 'o':
14272 base = 8;
14273 break;
14274 case 'x':
14275 case 'X':
14276 base = 16;
14277 break;
14278 }
14279
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014280 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14281 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014282 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014283 }
14284 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014285 return 1;
14286 }
14287
Ethan Furmanb95b5612015-01-23 20:05:18 -080014288 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014289 Py_DECREF(iobj);
14290 if (res == NULL)
14291 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014292 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014293 return 0;
14294
14295wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014296 switch(type)
14297 {
14298 case 'o':
14299 case 'x':
14300 case 'X':
14301 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014302 "%%%c format: an integer is required, "
14303 "not %.200s",
14304 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014305 break;
14306 default:
14307 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014308 "%%%c format: a number is required, "
14309 "not %.200s",
14310 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014311 break;
14312 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014313 return -1;
14314}
14315
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014316static Py_UCS4
14317formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014318{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014319 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014320 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014321 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014322 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014323 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014324 goto onError;
14325 }
14326 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014327 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014328 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014329 /* make sure number is a type of integer */
14330 if (!PyLong_Check(v)) {
14331 iobj = PyNumber_Index(v);
14332 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014333 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014334 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014335 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014336 Py_DECREF(iobj);
14337 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014338 else {
14339 x = PyLong_AsLong(v);
14340 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014341 if (x == -1 && PyErr_Occurred())
14342 goto onError;
14343
Victor Stinner8faf8212011-12-08 22:14:11 +010014344 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014345 PyErr_SetString(PyExc_OverflowError,
14346 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014347 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014348 }
14349
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014350 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014351 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014352
Benjamin Peterson29060642009-01-31 22:14:21 +000014353 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014354 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014355 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014356 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014357}
14358
Victor Stinnera47082312012-10-04 02:19:54 +020014359/* Parse options of an argument: flags, width, precision.
14360 Handle also "%(name)" syntax.
14361
14362 Return 0 if the argument has been formatted into arg->str.
14363 Return 1 if the argument has been written into ctx->writer,
14364 Raise an exception and return -1 on error. */
14365static int
14366unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14367 struct unicode_format_arg_t *arg)
14368{
14369#define FORMAT_READ(ctx) \
14370 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14371
14372 PyObject *v;
14373
Victor Stinnera47082312012-10-04 02:19:54 +020014374 if (arg->ch == '(') {
14375 /* Get argument value from a dictionary. Example: "%(name)s". */
14376 Py_ssize_t keystart;
14377 Py_ssize_t keylen;
14378 PyObject *key;
14379 int pcount = 1;
14380
14381 if (ctx->dict == NULL) {
14382 PyErr_SetString(PyExc_TypeError,
14383 "format requires a mapping");
14384 return -1;
14385 }
14386 ++ctx->fmtpos;
14387 --ctx->fmtcnt;
14388 keystart = ctx->fmtpos;
14389 /* Skip over balanced parentheses */
14390 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14391 arg->ch = FORMAT_READ(ctx);
14392 if (arg->ch == ')')
14393 --pcount;
14394 else if (arg->ch == '(')
14395 ++pcount;
14396 ctx->fmtpos++;
14397 }
14398 keylen = ctx->fmtpos - keystart - 1;
14399 if (ctx->fmtcnt < 0 || pcount > 0) {
14400 PyErr_SetString(PyExc_ValueError,
14401 "incomplete format key");
14402 return -1;
14403 }
14404 key = PyUnicode_Substring(ctx->fmtstr,
14405 keystart, keystart + keylen);
14406 if (key == NULL)
14407 return -1;
14408 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014409 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014410 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014411 }
14412 ctx->args = PyObject_GetItem(ctx->dict, key);
14413 Py_DECREF(key);
14414 if (ctx->args == NULL)
14415 return -1;
14416 ctx->args_owned = 1;
14417 ctx->arglen = -1;
14418 ctx->argidx = -2;
14419 }
14420
14421 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014422 while (--ctx->fmtcnt >= 0) {
14423 arg->ch = FORMAT_READ(ctx);
14424 ctx->fmtpos++;
14425 switch (arg->ch) {
14426 case '-': arg->flags |= F_LJUST; continue;
14427 case '+': arg->flags |= F_SIGN; continue;
14428 case ' ': arg->flags |= F_BLANK; continue;
14429 case '#': arg->flags |= F_ALT; continue;
14430 case '0': arg->flags |= F_ZERO; continue;
14431 }
14432 break;
14433 }
14434
14435 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014436 if (arg->ch == '*') {
14437 v = unicode_format_getnextarg(ctx);
14438 if (v == NULL)
14439 return -1;
14440 if (!PyLong_Check(v)) {
14441 PyErr_SetString(PyExc_TypeError,
14442 "* wants int");
14443 return -1;
14444 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014445 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014446 if (arg->width == -1 && PyErr_Occurred())
14447 return -1;
14448 if (arg->width < 0) {
14449 arg->flags |= F_LJUST;
14450 arg->width = -arg->width;
14451 }
14452 if (--ctx->fmtcnt >= 0) {
14453 arg->ch = FORMAT_READ(ctx);
14454 ctx->fmtpos++;
14455 }
14456 }
14457 else if (arg->ch >= '0' && arg->ch <= '9') {
14458 arg->width = arg->ch - '0';
14459 while (--ctx->fmtcnt >= 0) {
14460 arg->ch = FORMAT_READ(ctx);
14461 ctx->fmtpos++;
14462 if (arg->ch < '0' || arg->ch > '9')
14463 break;
14464 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14465 mixing signed and unsigned comparison. Since arg->ch is between
14466 '0' and '9', casting to int is safe. */
14467 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14468 PyErr_SetString(PyExc_ValueError,
14469 "width too big");
14470 return -1;
14471 }
14472 arg->width = arg->width*10 + (arg->ch - '0');
14473 }
14474 }
14475
14476 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014477 if (arg->ch == '.') {
14478 arg->prec = 0;
14479 if (--ctx->fmtcnt >= 0) {
14480 arg->ch = FORMAT_READ(ctx);
14481 ctx->fmtpos++;
14482 }
14483 if (arg->ch == '*') {
14484 v = unicode_format_getnextarg(ctx);
14485 if (v == NULL)
14486 return -1;
14487 if (!PyLong_Check(v)) {
14488 PyErr_SetString(PyExc_TypeError,
14489 "* wants int");
14490 return -1;
14491 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014492 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014493 if (arg->prec == -1 && PyErr_Occurred())
14494 return -1;
14495 if (arg->prec < 0)
14496 arg->prec = 0;
14497 if (--ctx->fmtcnt >= 0) {
14498 arg->ch = FORMAT_READ(ctx);
14499 ctx->fmtpos++;
14500 }
14501 }
14502 else if (arg->ch >= '0' && arg->ch <= '9') {
14503 arg->prec = arg->ch - '0';
14504 while (--ctx->fmtcnt >= 0) {
14505 arg->ch = FORMAT_READ(ctx);
14506 ctx->fmtpos++;
14507 if (arg->ch < '0' || arg->ch > '9')
14508 break;
14509 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14510 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014511 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014512 return -1;
14513 }
14514 arg->prec = arg->prec*10 + (arg->ch - '0');
14515 }
14516 }
14517 }
14518
14519 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14520 if (ctx->fmtcnt >= 0) {
14521 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14522 if (--ctx->fmtcnt >= 0) {
14523 arg->ch = FORMAT_READ(ctx);
14524 ctx->fmtpos++;
14525 }
14526 }
14527 }
14528 if (ctx->fmtcnt < 0) {
14529 PyErr_SetString(PyExc_ValueError,
14530 "incomplete format");
14531 return -1;
14532 }
14533 return 0;
14534
14535#undef FORMAT_READ
14536}
14537
14538/* Format one argument. Supported conversion specifiers:
14539
14540 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014541 - "i", "d", "u": int or float
14542 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014543 - "e", "E", "f", "F", "g", "G": float
14544 - "c": int or str (1 character)
14545
Victor Stinner8dbd4212012-12-04 09:30:24 +010014546 When possible, the output is written directly into the Unicode writer
14547 (ctx->writer). A string is created when padding is required.
14548
Victor Stinnera47082312012-10-04 02:19:54 +020014549 Return 0 if the argument has been formatted into *p_str,
14550 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014551 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014552static int
14553unicode_format_arg_format(struct unicode_formatter_t *ctx,
14554 struct unicode_format_arg_t *arg,
14555 PyObject **p_str)
14556{
14557 PyObject *v;
14558 _PyUnicodeWriter *writer = &ctx->writer;
14559
14560 if (ctx->fmtcnt == 0)
14561 ctx->writer.overallocate = 0;
14562
Victor Stinnera47082312012-10-04 02:19:54 +020014563 v = unicode_format_getnextarg(ctx);
14564 if (v == NULL)
14565 return -1;
14566
Victor Stinnera47082312012-10-04 02:19:54 +020014567
14568 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014569 case 's':
14570 case 'r':
14571 case 'a':
14572 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14573 /* Fast path */
14574 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14575 return -1;
14576 return 1;
14577 }
14578
14579 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14580 *p_str = v;
14581 Py_INCREF(*p_str);
14582 }
14583 else {
14584 if (arg->ch == 's')
14585 *p_str = PyObject_Str(v);
14586 else if (arg->ch == 'r')
14587 *p_str = PyObject_Repr(v);
14588 else
14589 *p_str = PyObject_ASCII(v);
14590 }
14591 break;
14592
14593 case 'i':
14594 case 'd':
14595 case 'u':
14596 case 'o':
14597 case 'x':
14598 case 'X':
14599 {
14600 int ret = mainformatlong(v, arg, p_str, writer);
14601 if (ret != 0)
14602 return ret;
14603 arg->sign = 1;
14604 break;
14605 }
14606
14607 case 'e':
14608 case 'E':
14609 case 'f':
14610 case 'F':
14611 case 'g':
14612 case 'G':
14613 if (arg->width == -1 && arg->prec == -1
14614 && !(arg->flags & (F_SIGN | F_BLANK)))
14615 {
14616 /* Fast path */
14617 if (formatfloat(v, arg, NULL, writer) == -1)
14618 return -1;
14619 return 1;
14620 }
14621
14622 arg->sign = 1;
14623 if (formatfloat(v, arg, p_str, NULL) == -1)
14624 return -1;
14625 break;
14626
14627 case 'c':
14628 {
14629 Py_UCS4 ch = formatchar(v);
14630 if (ch == (Py_UCS4) -1)
14631 return -1;
14632 if (arg->width == -1 && arg->prec == -1) {
14633 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014634 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014635 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014636 return 1;
14637 }
14638 *p_str = PyUnicode_FromOrdinal(ch);
14639 break;
14640 }
14641
14642 default:
14643 PyErr_Format(PyExc_ValueError,
14644 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014645 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014646 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14647 (int)arg->ch,
14648 ctx->fmtpos - 1);
14649 return -1;
14650 }
14651 if (*p_str == NULL)
14652 return -1;
14653 assert (PyUnicode_Check(*p_str));
14654 return 0;
14655}
14656
14657static int
14658unicode_format_arg_output(struct unicode_formatter_t *ctx,
14659 struct unicode_format_arg_t *arg,
14660 PyObject *str)
14661{
14662 Py_ssize_t len;
14663 enum PyUnicode_Kind kind;
14664 void *pbuf;
14665 Py_ssize_t pindex;
14666 Py_UCS4 signchar;
14667 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014668 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014669 Py_ssize_t sublen;
14670 _PyUnicodeWriter *writer = &ctx->writer;
14671 Py_UCS4 fill;
14672
14673 fill = ' ';
14674 if (arg->sign && arg->flags & F_ZERO)
14675 fill = '0';
14676
14677 if (PyUnicode_READY(str) == -1)
14678 return -1;
14679
14680 len = PyUnicode_GET_LENGTH(str);
14681 if ((arg->width == -1 || arg->width <= len)
14682 && (arg->prec == -1 || arg->prec >= len)
14683 && !(arg->flags & (F_SIGN | F_BLANK)))
14684 {
14685 /* Fast path */
14686 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14687 return -1;
14688 return 0;
14689 }
14690
14691 /* Truncate the string for "s", "r" and "a" formats
14692 if the precision is set */
14693 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14694 if (arg->prec >= 0 && len > arg->prec)
14695 len = arg->prec;
14696 }
14697
14698 /* Adjust sign and width */
14699 kind = PyUnicode_KIND(str);
14700 pbuf = PyUnicode_DATA(str);
14701 pindex = 0;
14702 signchar = '\0';
14703 if (arg->sign) {
14704 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14705 if (ch == '-' || ch == '+') {
14706 signchar = ch;
14707 len--;
14708 pindex++;
14709 }
14710 else if (arg->flags & F_SIGN)
14711 signchar = '+';
14712 else if (arg->flags & F_BLANK)
14713 signchar = ' ';
14714 else
14715 arg->sign = 0;
14716 }
14717 if (arg->width < len)
14718 arg->width = len;
14719
14720 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014721 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014722 if (!(arg->flags & F_LJUST)) {
14723 if (arg->sign) {
14724 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014725 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014726 }
14727 else {
14728 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014729 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014730 }
14731 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014732 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14733 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014734 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014735 }
14736
Victor Stinnera47082312012-10-04 02:19:54 +020014737 buflen = arg->width;
14738 if (arg->sign && len == arg->width)
14739 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014740 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014741 return -1;
14742
14743 /* Write the sign if needed */
14744 if (arg->sign) {
14745 if (fill != ' ') {
14746 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14747 writer->pos += 1;
14748 }
14749 if (arg->width > len)
14750 arg->width--;
14751 }
14752
14753 /* Write the numeric prefix for "x", "X" and "o" formats
14754 if the alternate form is used.
14755 For example, write "0x" for the "%#x" format. */
14756 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14757 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14758 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14759 if (fill != ' ') {
14760 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14761 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14762 writer->pos += 2;
14763 pindex += 2;
14764 }
14765 arg->width -= 2;
14766 if (arg->width < 0)
14767 arg->width = 0;
14768 len -= 2;
14769 }
14770
14771 /* Pad left with the fill character if needed */
14772 if (arg->width > len && !(arg->flags & F_LJUST)) {
14773 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014774 unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014775 writer->pos += sublen;
14776 arg->width = len;
14777 }
14778
14779 /* If padding with spaces: write sign if needed and/or numeric prefix if
14780 the alternate form is used */
14781 if (fill == ' ') {
14782 if (arg->sign) {
14783 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14784 writer->pos += 1;
14785 }
14786 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14787 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14788 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14789 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14790 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14791 writer->pos += 2;
14792 pindex += 2;
14793 }
14794 }
14795
14796 /* Write characters */
14797 if (len) {
14798 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14799 str, pindex, len);
14800 writer->pos += len;
14801 }
14802
14803 /* Pad right with the fill character if needed */
14804 if (arg->width > len) {
14805 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014806 unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014807 writer->pos += sublen;
14808 }
14809 return 0;
14810}
14811
14812/* Helper of PyUnicode_Format(): format one arg.
14813 Return 0 on success, raise an exception and return -1 on error. */
14814static int
14815unicode_format_arg(struct unicode_formatter_t *ctx)
14816{
14817 struct unicode_format_arg_t arg;
14818 PyObject *str;
14819 int ret;
14820
Victor Stinner8dbd4212012-12-04 09:30:24 +010014821 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014822 if (arg.ch == '%') {
14823 ctx->fmtpos++;
14824 ctx->fmtcnt--;
14825 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14826 return -1;
14827 return 0;
14828 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014829 arg.flags = 0;
14830 arg.width = -1;
14831 arg.prec = -1;
14832 arg.sign = 0;
14833 str = NULL;
14834
Victor Stinnera47082312012-10-04 02:19:54 +020014835 ret = unicode_format_arg_parse(ctx, &arg);
14836 if (ret == -1)
14837 return -1;
14838
14839 ret = unicode_format_arg_format(ctx, &arg, &str);
14840 if (ret == -1)
14841 return -1;
14842
14843 if (ret != 1) {
14844 ret = unicode_format_arg_output(ctx, &arg, str);
14845 Py_DECREF(str);
14846 if (ret == -1)
14847 return -1;
14848 }
14849
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014850 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014851 PyErr_SetString(PyExc_TypeError,
14852 "not all arguments converted during string formatting");
14853 return -1;
14854 }
14855 return 0;
14856}
14857
Alexander Belopolsky40018472011-02-26 01:02:56 +000014858PyObject *
14859PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014860{
Victor Stinnera47082312012-10-04 02:19:54 +020014861 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014862
Guido van Rossumd57fd912000-03-10 22:53:23 +000014863 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014864 PyErr_BadInternalCall();
14865 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014866 }
Victor Stinnera47082312012-10-04 02:19:54 +020014867
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014868 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014869 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014870
14871 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014872 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14873 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14874 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14875 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014876
Victor Stinner8f674cc2013-04-17 23:02:17 +020014877 _PyUnicodeWriter_Init(&ctx.writer);
14878 ctx.writer.min_length = ctx.fmtcnt + 100;
14879 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014880
Guido van Rossumd57fd912000-03-10 22:53:23 +000014881 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014882 ctx.arglen = PyTuple_Size(args);
14883 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014884 }
14885 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014886 ctx.arglen = -1;
14887 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014888 }
Victor Stinnera47082312012-10-04 02:19:54 +020014889 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014890 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014891 ctx.dict = args;
14892 else
14893 ctx.dict = NULL;
14894 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014895
Victor Stinnera47082312012-10-04 02:19:54 +020014896 while (--ctx.fmtcnt >= 0) {
14897 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014898 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014899
14900 nonfmtpos = ctx.fmtpos++;
14901 while (ctx.fmtcnt >= 0 &&
14902 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14903 ctx.fmtpos++;
14904 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014905 }
Victor Stinnera47082312012-10-04 02:19:54 +020014906 if (ctx.fmtcnt < 0) {
14907 ctx.fmtpos--;
14908 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014909 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014910
Victor Stinnercfc4c132013-04-03 01:48:39 +020014911 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14912 nonfmtpos, ctx.fmtpos) < 0)
14913 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014914 }
14915 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014916 ctx.fmtpos++;
14917 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014918 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014919 }
14920 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014921
Victor Stinnera47082312012-10-04 02:19:54 +020014922 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014923 PyErr_SetString(PyExc_TypeError,
14924 "not all arguments converted during string formatting");
14925 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014926 }
14927
Victor Stinnera47082312012-10-04 02:19:54 +020014928 if (ctx.args_owned) {
14929 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014930 }
Victor Stinnera47082312012-10-04 02:19:54 +020014931 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014932
Benjamin Peterson29060642009-01-31 22:14:21 +000014933 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014934 _PyUnicodeWriter_Dealloc(&ctx.writer);
14935 if (ctx.args_owned) {
14936 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014937 }
14938 return NULL;
14939}
14940
Jeremy Hylton938ace62002-07-17 16:30:39 +000014941static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014942unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14943
Tim Peters6d6c1a32001-08-02 04:15:00 +000014944static PyObject *
14945unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14946{
Benjamin Peterson29060642009-01-31 22:14:21 +000014947 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014948 static char *kwlist[] = {"object", "encoding", "errors", 0};
14949 char *encoding = NULL;
14950 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014951
Benjamin Peterson14339b62009-01-31 16:36:08 +000014952 if (type != &PyUnicode_Type)
14953 return unicode_subtype_new(type, args, kwds);
14954 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014955 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014956 return NULL;
14957 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014958 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014959 if (encoding == NULL && errors == NULL)
14960 return PyObject_Str(x);
14961 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014962 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014963}
14964
Guido van Rossume023fe02001-08-30 03:12:59 +000014965static PyObject *
14966unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14967{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014968 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014969 Py_ssize_t length, char_size;
14970 int share_wstr, share_utf8;
14971 unsigned int kind;
14972 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014973
Benjamin Peterson14339b62009-01-31 16:36:08 +000014974 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014975
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014976 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014977 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014978 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014979 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014980 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014981 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014982 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014983 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014984
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014985 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014986 if (self == NULL) {
14987 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014988 return NULL;
14989 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014990 kind = PyUnicode_KIND(unicode);
14991 length = PyUnicode_GET_LENGTH(unicode);
14992
14993 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014994#ifdef Py_DEBUG
14995 _PyUnicode_HASH(self) = -1;
14996#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014997 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014998#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014999 _PyUnicode_STATE(self).interned = 0;
15000 _PyUnicode_STATE(self).kind = kind;
15001 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015002 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015003 _PyUnicode_STATE(self).ready = 1;
15004 _PyUnicode_WSTR(self) = NULL;
15005 _PyUnicode_UTF8_LENGTH(self) = 0;
15006 _PyUnicode_UTF8(self) = NULL;
15007 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015008 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015009
15010 share_utf8 = 0;
15011 share_wstr = 0;
15012 if (kind == PyUnicode_1BYTE_KIND) {
15013 char_size = 1;
15014 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15015 share_utf8 = 1;
15016 }
15017 else if (kind == PyUnicode_2BYTE_KIND) {
15018 char_size = 2;
15019 if (sizeof(wchar_t) == 2)
15020 share_wstr = 1;
15021 }
15022 else {
15023 assert(kind == PyUnicode_4BYTE_KIND);
15024 char_size = 4;
15025 if (sizeof(wchar_t) == 4)
15026 share_wstr = 1;
15027 }
15028
15029 /* Ensure we won't overflow the length. */
15030 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15031 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015032 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015033 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015034 data = PyObject_MALLOC((length + 1) * char_size);
15035 if (data == NULL) {
15036 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015037 goto onError;
15038 }
15039
Victor Stinnerc3c74152011-10-02 20:39:55 +020015040 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015041 if (share_utf8) {
15042 _PyUnicode_UTF8_LENGTH(self) = length;
15043 _PyUnicode_UTF8(self) = data;
15044 }
15045 if (share_wstr) {
15046 _PyUnicode_WSTR_LENGTH(self) = length;
15047 _PyUnicode_WSTR(self) = (wchar_t *)data;
15048 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015049
Christian Heimesf051e432016-09-13 20:22:02 +020015050 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015051 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015052 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015053#ifdef Py_DEBUG
15054 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15055#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015056 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015057 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015058
15059onError:
15060 Py_DECREF(unicode);
15061 Py_DECREF(self);
15062 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015063}
15064
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015065PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015066"str(object='') -> str\n\
15067str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015068\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015069Create a new string object from the given object. If encoding or\n\
15070errors is specified, then the object must expose a data buffer\n\
15071that will be decoded using the given encoding and error handler.\n\
15072Otherwise, returns the result of object.__str__() (if defined)\n\
15073or repr(object).\n\
15074encoding defaults to sys.getdefaultencoding().\n\
15075errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015076
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015077static PyObject *unicode_iter(PyObject *seq);
15078
Guido van Rossumd57fd912000-03-10 22:53:23 +000015079PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015080 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015081 "str", /* tp_name */
15082 sizeof(PyUnicodeObject), /* tp_basicsize */
15083 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015084 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015085 (destructor)unicode_dealloc, /* tp_dealloc */
15086 0, /* tp_print */
15087 0, /* tp_getattr */
15088 0, /* tp_setattr */
15089 0, /* tp_reserved */
15090 unicode_repr, /* tp_repr */
15091 &unicode_as_number, /* tp_as_number */
15092 &unicode_as_sequence, /* tp_as_sequence */
15093 &unicode_as_mapping, /* tp_as_mapping */
15094 (hashfunc) unicode_hash, /* tp_hash*/
15095 0, /* tp_call*/
15096 (reprfunc) unicode_str, /* tp_str */
15097 PyObject_GenericGetAttr, /* tp_getattro */
15098 0, /* tp_setattro */
15099 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015100 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015101 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15102 unicode_doc, /* tp_doc */
15103 0, /* tp_traverse */
15104 0, /* tp_clear */
15105 PyUnicode_RichCompare, /* tp_richcompare */
15106 0, /* tp_weaklistoffset */
15107 unicode_iter, /* tp_iter */
15108 0, /* tp_iternext */
15109 unicode_methods, /* tp_methods */
15110 0, /* tp_members */
15111 0, /* tp_getset */
15112 &PyBaseObject_Type, /* tp_base */
15113 0, /* tp_dict */
15114 0, /* tp_descr_get */
15115 0, /* tp_descr_set */
15116 0, /* tp_dictoffset */
15117 0, /* tp_init */
15118 0, /* tp_alloc */
15119 unicode_new, /* tp_new */
15120 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015121};
15122
15123/* Initialize the Unicode implementation */
15124
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015125_PyInitError
15126_PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015127{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015128 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015129 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015130 0x000A, /* LINE FEED */
15131 0x000D, /* CARRIAGE RETURN */
15132 0x001C, /* FILE SEPARATOR */
15133 0x001D, /* GROUP SEPARATOR */
15134 0x001E, /* RECORD SEPARATOR */
15135 0x0085, /* NEXT LINE */
15136 0x2028, /* LINE SEPARATOR */
15137 0x2029, /* PARAGRAPH SEPARATOR */
15138 };
15139
Fred Drakee4315f52000-05-09 19:53:39 +000015140 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015141 _Py_INCREF_UNICODE_EMPTY();
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015142 if (!unicode_empty) {
15143 return _Py_INIT_ERR("Can't create empty string");
15144 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020015145 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015146
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015147 if (PyType_Ready(&PyUnicode_Type) < 0) {
15148 return _Py_INIT_ERR("Can't initialize unicode type");
15149 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015150
15151 /* initialize the linebreak bloom filter */
15152 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015153 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015154 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015155
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015156 if (PyType_Ready(&EncodingMapType) < 0) {
15157 return _Py_INIT_ERR("Can't initialize encoding map type");
15158 }
15159 if (PyType_Ready(&PyFieldNameIter_Type) < 0) {
15160 return _Py_INIT_ERR("Can't initialize field name iterator type");
15161 }
15162 if (PyType_Ready(&PyFormatterIter_Type) < 0) {
15163 return _Py_INIT_ERR("Can't initialize formatter iter type");
15164 }
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015165 return _Py_INIT_OK();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015166}
15167
15168/* Finalize the Unicode implementation */
15169
Christian Heimesa156e092008-02-16 07:38:31 +000015170int
15171PyUnicode_ClearFreeList(void)
15172{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015173 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015174}
15175
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015176
Walter Dörwald16807132007-05-25 13:52:07 +000015177void
15178PyUnicode_InternInPlace(PyObject **p)
15179{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015180 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015181 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015182#ifdef Py_DEBUG
15183 assert(s != NULL);
15184 assert(_PyUnicode_CHECK(s));
15185#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015186 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015187 return;
15188#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015189 /* If it's a subclass, we don't really know what putting
15190 it in the interned dict might do. */
15191 if (!PyUnicode_CheckExact(s))
15192 return;
15193 if (PyUnicode_CHECK_INTERNED(s))
15194 return;
15195 if (interned == NULL) {
15196 interned = PyDict_New();
15197 if (interned == NULL) {
15198 PyErr_Clear(); /* Don't leave an exception */
15199 return;
15200 }
15201 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015202 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015203 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015204 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015205 if (t == NULL) {
15206 PyErr_Clear();
15207 return;
15208 }
15209 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015210 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015211 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015212 return;
15213 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015214 /* The two references in interned are not counted by refcnt.
15215 The deallocator will take care of this */
15216 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015217 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015218}
15219
15220void
15221PyUnicode_InternImmortal(PyObject **p)
15222{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015223 PyUnicode_InternInPlace(p);
15224 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015225 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015226 Py_INCREF(*p);
15227 }
Walter Dörwald16807132007-05-25 13:52:07 +000015228}
15229
15230PyObject *
15231PyUnicode_InternFromString(const char *cp)
15232{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015233 PyObject *s = PyUnicode_FromString(cp);
15234 if (s == NULL)
15235 return NULL;
15236 PyUnicode_InternInPlace(&s);
15237 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015238}
15239
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015240
15241#if defined(WITH_VALGRIND) || defined(__INSURE__)
15242static void
15243unicode_release_interned(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015244{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015245 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015246 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015247 Py_ssize_t i, n;
15248 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015249
Benjamin Peterson14339b62009-01-31 16:36:08 +000015250 if (interned == NULL || !PyDict_Check(interned))
15251 return;
15252 keys = PyDict_Keys(interned);
15253 if (keys == NULL || !PyList_Check(keys)) {
15254 PyErr_Clear();
15255 return;
15256 }
Walter Dörwald16807132007-05-25 13:52:07 +000015257
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015258 /* Since unicode_release_interned() is intended to help a leak
Benjamin Peterson14339b62009-01-31 16:36:08 +000015259 detector, interned unicode strings are not forcibly deallocated;
15260 rather, we give them their stolen references back, and then clear
15261 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015262
Benjamin Peterson14339b62009-01-31 16:36:08 +000015263 n = PyList_GET_SIZE(keys);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015264#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015265 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015266 n);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015267#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015269 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015270 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015271 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015272 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015273 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015274 case SSTATE_NOT_INTERNED:
15275 /* XXX Shouldn't happen */
15276 break;
15277 case SSTATE_INTERNED_IMMORTAL:
15278 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015279 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015280 break;
15281 case SSTATE_INTERNED_MORTAL:
15282 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015283 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015284 break;
15285 default:
15286 Py_FatalError("Inconsistent interned string state.");
15287 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015288 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015289 }
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015290#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015291 fprintf(stderr, "total size of all interned strings: "
15292 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15293 "mortal/immortal\n", mortal_size, immortal_size);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015294#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015295 Py_DECREF(keys);
15296 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015297 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015298}
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015299#endif
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015300
15301
15302/********************* Unicode Iterator **************************/
15303
15304typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015305 PyObject_HEAD
15306 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015307 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015308} unicodeiterobject;
15309
15310static void
15311unicodeiter_dealloc(unicodeiterobject *it)
15312{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015313 _PyObject_GC_UNTRACK(it);
15314 Py_XDECREF(it->it_seq);
15315 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015316}
15317
15318static int
15319unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15320{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015321 Py_VISIT(it->it_seq);
15322 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015323}
15324
15325static PyObject *
15326unicodeiter_next(unicodeiterobject *it)
15327{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015328 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015329
Benjamin Peterson14339b62009-01-31 16:36:08 +000015330 assert(it != NULL);
15331 seq = it->it_seq;
15332 if (seq == NULL)
15333 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015334 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015336 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15337 int kind = PyUnicode_KIND(seq);
15338 void *data = PyUnicode_DATA(seq);
15339 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15340 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015341 if (item != NULL)
15342 ++it->it_index;
15343 return item;
15344 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015345
Benjamin Peterson14339b62009-01-31 16:36:08 +000015346 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015347 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015348 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015349}
15350
15351static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015352unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015353{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015354 Py_ssize_t len = 0;
15355 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015356 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015357 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015358}
15359
15360PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15361
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015362static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015363unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015364{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015365 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015366 if (it->it_seq != NULL) {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015367 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015368 it->it_seq, it->it_index);
15369 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015370 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015371 if (u == NULL)
15372 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015373 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015374 }
15375}
15376
15377PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15378
15379static PyObject *
15380unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15381{
15382 Py_ssize_t index = PyLong_AsSsize_t(state);
15383 if (index == -1 && PyErr_Occurred())
15384 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015385 if (it->it_seq != NULL) {
15386 if (index < 0)
15387 index = 0;
15388 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15389 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15390 it->it_index = index;
15391 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015392 Py_RETURN_NONE;
15393}
15394
15395PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15396
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015397static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015398 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015399 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015400 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15401 reduce_doc},
15402 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15403 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015404 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015405};
15406
15407PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015408 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15409 "str_iterator", /* tp_name */
15410 sizeof(unicodeiterobject), /* tp_basicsize */
15411 0, /* tp_itemsize */
15412 /* methods */
15413 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15414 0, /* tp_print */
15415 0, /* tp_getattr */
15416 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015417 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015418 0, /* tp_repr */
15419 0, /* tp_as_number */
15420 0, /* tp_as_sequence */
15421 0, /* tp_as_mapping */
15422 0, /* tp_hash */
15423 0, /* tp_call */
15424 0, /* tp_str */
15425 PyObject_GenericGetAttr, /* tp_getattro */
15426 0, /* tp_setattro */
15427 0, /* tp_as_buffer */
15428 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15429 0, /* tp_doc */
15430 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15431 0, /* tp_clear */
15432 0, /* tp_richcompare */
15433 0, /* tp_weaklistoffset */
15434 PyObject_SelfIter, /* tp_iter */
15435 (iternextfunc)unicodeiter_next, /* tp_iternext */
15436 unicodeiter_methods, /* tp_methods */
15437 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015438};
15439
15440static PyObject *
15441unicode_iter(PyObject *seq)
15442{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015443 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015444
Benjamin Peterson14339b62009-01-31 16:36:08 +000015445 if (!PyUnicode_Check(seq)) {
15446 PyErr_BadInternalCall();
15447 return NULL;
15448 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015449 if (PyUnicode_READY(seq) == -1)
15450 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015451 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15452 if (it == NULL)
15453 return NULL;
15454 it->it_index = 0;
15455 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015456 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015457 _PyObject_GC_TRACK(it);
15458 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015459}
15460
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015461
15462size_t
15463Py_UNICODE_strlen(const Py_UNICODE *u)
15464{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015465 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015466}
15467
15468Py_UNICODE*
15469Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15470{
15471 Py_UNICODE *u = s1;
15472 while ((*u++ = *s2++));
15473 return s1;
15474}
15475
15476Py_UNICODE*
15477Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15478{
15479 Py_UNICODE *u = s1;
15480 while ((*u++ = *s2++))
15481 if (n-- == 0)
15482 break;
15483 return s1;
15484}
15485
15486Py_UNICODE*
15487Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15488{
15489 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015490 u1 += wcslen(u1);
15491 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015492 return s1;
15493}
15494
15495int
15496Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15497{
15498 while (*s1 && *s2 && *s1 == *s2)
15499 s1++, s2++;
15500 if (*s1 && *s2)
15501 return (*s1 < *s2) ? -1 : +1;
15502 if (*s1)
15503 return 1;
15504 if (*s2)
15505 return -1;
15506 return 0;
15507}
15508
15509int
15510Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15511{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015512 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015513 for (; n != 0; n--) {
15514 u1 = *s1;
15515 u2 = *s2;
15516 if (u1 != u2)
15517 return (u1 < u2) ? -1 : +1;
15518 if (u1 == '\0')
15519 return 0;
15520 s1++;
15521 s2++;
15522 }
15523 return 0;
15524}
15525
15526Py_UNICODE*
15527Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15528{
15529 const Py_UNICODE *p;
15530 for (p = s; *p; p++)
15531 if (*p == c)
15532 return (Py_UNICODE*)p;
15533 return NULL;
15534}
15535
15536Py_UNICODE*
15537Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15538{
15539 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015540 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015541 while (p != s) {
15542 p--;
15543 if (*p == c)
15544 return (Py_UNICODE*)p;
15545 }
15546 return NULL;
15547}
Victor Stinner331ea922010-08-10 16:37:20 +000015548
Victor Stinner71133ff2010-09-01 23:43:53 +000015549Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015550PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015551{
Victor Stinner577db2c2011-10-11 22:12:48 +020015552 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015553 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015555 if (!PyUnicode_Check(unicode)) {
15556 PyErr_BadArgument();
15557 return NULL;
15558 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015559 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015560 if (u == NULL)
15561 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015562 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015563 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015564 PyErr_NoMemory();
15565 return NULL;
15566 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015567 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015568 size *= sizeof(Py_UNICODE);
15569 copy = PyMem_Malloc(size);
15570 if (copy == NULL) {
15571 PyErr_NoMemory();
15572 return NULL;
15573 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015574 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015575 return copy;
15576}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015577
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015578
15579void
15580_PyUnicode_Fini(void)
15581{
15582#if defined(WITH_VALGRIND) || defined(__INSURE__)
15583 /* Insure++ is a memory analysis tool that aids in discovering
15584 * memory leaks and other memory problems. On Python exit, the
15585 * interned string dictionaries are flagged as being in use at exit
15586 * (which it is). Under normal circumstances, this is fine because
15587 * the memory will be automatically reclaimed by the system. Under
15588 * memory debugging, it's a huge source of useless noise, so we
15589 * trade off slower shutdown for less distraction in the memory
15590 * reports. -baw
15591 */
15592 unicode_release_interned();
15593#endif /* __INSURE__ */
15594
15595 Py_CLEAR(unicode_empty);
15596
15597 for (Py_ssize_t i = 0; i < 256; i++) {
15598 Py_CLEAR(unicode_latin1[i]);
15599 }
15600 _PyUnicode_ClearStaticStrings();
15601 (void)PyUnicode_ClearFreeList();
15602}
15603
15604
Georg Brandl66c221e2010-10-14 07:04:07 +000015605/* A _string module, to export formatter_parser and formatter_field_name_split
15606 to the string.Formatter class implemented in Python. */
15607
15608static PyMethodDef _string_methods[] = {
15609 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15610 METH_O, PyDoc_STR("split the argument as a field name")},
15611 {"formatter_parser", (PyCFunction) formatter_parser,
15612 METH_O, PyDoc_STR("parse the argument as a format string")},
15613 {NULL, NULL}
15614};
15615
15616static struct PyModuleDef _string_module = {
15617 PyModuleDef_HEAD_INIT,
15618 "_string",
15619 PyDoc_STR("string helper module"),
15620 0,
15621 _string_methods,
15622 NULL,
15623 NULL,
15624 NULL,
15625 NULL
15626};
15627
15628PyMODINIT_FUNC
15629PyInit__string(void)
15630{
15631 return PyModule_Create(&_string_module);
15632}
15633
15634
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015635#ifdef __cplusplus
15636}
15637#endif