blob: 6e83ed6bdd432c229e2d1e41c4bf0ab4d3ee8acd [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{
Victor Stinner3a50e702011-10-18 21:21:00 +02007086 const DWORD flags = decode_code_page_flags(code_page);
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);
7092 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7093 if (outsize <= 0)
7094 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007095
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007096 /* Extend a wchar_t* buffer */
7097 Py_ssize_t n = *bufsize; /* Get the current length */
7098 if (widechar_resize(buf, bufsize, n + outsize) < 0) {
7099 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007100 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007101 out = *buf + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007102
7103 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007104 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7105 if (outsize <= 0)
7106 goto error;
7107 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007108
Victor Stinner3a50e702011-10-18 21:21:00 +02007109error:
7110 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7111 return -2;
7112 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007113 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114}
7115
Victor Stinner3a50e702011-10-18 21:21:00 +02007116/*
7117 * Decode a byte string from a code page into unicode object with an error
7118 * handler.
7119 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007120 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007121 * UnicodeDecodeError exception and returns -1 on error.
7122 */
7123static int
7124decode_code_page_errors(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007125 wchar_t **buf,
7126 Py_ssize_t *bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007127 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007128 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007129{
7130 const char *startin = in;
7131 const char *endin = in + size;
7132 const DWORD flags = decode_code_page_flags(code_page);
7133 /* Ideally, we should get reason from FormatMessage. This is the Windows
7134 2000 English version of the message. */
7135 const char *reason = "No mapping for the Unicode character exists "
7136 "in the target code page.";
7137 /* each step cannot decode more than 1 character, but a character can be
7138 represented as a surrogate pair */
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007139 wchar_t buffer[2], *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007140 int insize;
7141 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007142 PyObject *errorHandler = NULL;
7143 PyObject *exc = NULL;
7144 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007145 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007146 DWORD err;
7147 int ret = -1;
7148
7149 assert(size > 0);
7150
7151 encoding = code_page_name(code_page, &encoding_obj);
7152 if (encoding == NULL)
7153 return -1;
7154
Victor Stinner7d00cc12014-03-17 23:08:06 +01007155 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007156 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7157 UnicodeDecodeError. */
7158 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7159 if (exc != NULL) {
7160 PyCodec_StrictErrors(exc);
7161 Py_CLEAR(exc);
7162 }
7163 goto error;
7164 }
7165
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007166 /* Extend a wchar_t* buffer */
7167 Py_ssize_t n = *bufsize; /* Get the current length */
7168 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7169 PyErr_NoMemory();
7170 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007171 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007172 if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
7173 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007175 out = *buf + n;
Victor Stinner3a50e702011-10-18 21:21:00 +02007176
7177 /* Decode the byte string character per character */
Victor Stinner3a50e702011-10-18 21:21:00 +02007178 while (in < endin)
7179 {
7180 /* Decode a character */
7181 insize = 1;
7182 do
7183 {
7184 outsize = MultiByteToWideChar(code_page, flags,
7185 in, insize,
7186 buffer, Py_ARRAY_LENGTH(buffer));
7187 if (outsize > 0)
7188 break;
7189 err = GetLastError();
7190 if (err != ERROR_NO_UNICODE_TRANSLATION
7191 && err != ERROR_INSUFFICIENT_BUFFER)
7192 {
7193 PyErr_SetFromWindowsErr(0);
7194 goto error;
7195 }
7196 insize++;
7197 }
7198 /* 4=maximum length of a UTF-8 sequence */
7199 while (insize <= 4 && (in + insize) <= endin);
7200
7201 if (outsize <= 0) {
7202 Py_ssize_t startinpos, endinpos, outpos;
7203
Victor Stinner7d00cc12014-03-17 23:08:06 +01007204 /* last character in partial decode? */
7205 if (in + insize >= endin && !final)
7206 break;
7207
Victor Stinner3a50e702011-10-18 21:21:00 +02007208 startinpos = in - startin;
7209 endinpos = startinpos + 1;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007210 outpos = out - *buf;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007211 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007212 errors, &errorHandler,
7213 encoding, reason,
7214 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007215 buf, bufsize, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 {
7217 goto error;
7218 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007219 out = *buf + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 }
7221 else {
7222 in += insize;
7223 memcpy(out, buffer, outsize * sizeof(wchar_t));
7224 out += outsize;
7225 }
7226 }
7227
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007228 /* Shrink the buffer */
7229 assert(out - *buf <= *bufsize);
7230 *bufsize = out - *buf;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007231 /* (in - startin) <= size and size is an int */
7232 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007233
7234error:
7235 Py_XDECREF(encoding_obj);
7236 Py_XDECREF(errorHandler);
7237 Py_XDECREF(exc);
7238 return ret;
7239}
7240
Victor Stinner3a50e702011-10-18 21:21:00 +02007241static PyObject *
7242decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007243 const char *s, Py_ssize_t size,
7244 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007245{
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007246 wchar_t *buf = NULL;
7247 Py_ssize_t bufsize = 0;
Victor Stinner76a31a62011-11-04 00:05:13 +01007248 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007249
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 if (code_page < 0) {
7251 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7252 return NULL;
7253 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007254 if (size < 0) {
7255 PyErr_BadInternalCall();
7256 return NULL;
7257 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007258
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007259 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007260 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261
Victor Stinner76a31a62011-11-04 00:05:13 +01007262 do
7263 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007264#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007265 if (size > INT_MAX) {
7266 chunk_size = INT_MAX;
7267 final = 0;
7268 done = 0;
7269 }
7270 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007271#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007272 {
7273 chunk_size = (int)size;
7274 final = (consumed == NULL);
7275 done = 1;
7276 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007277
Victor Stinner76a31a62011-11-04 00:05:13 +01007278 if (chunk_size == 0 && done) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007279 if (buf != NULL)
Victor Stinner76a31a62011-11-04 00:05:13 +01007280 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007281 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007282 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007283
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007284 converted = decode_code_page_strict(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007285 s, chunk_size);
7286 if (converted == -2)
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007287 converted = decode_code_page_errors(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007288 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007289 errors, final);
7290 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007291
7292 if (converted < 0) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007293 PyMem_Free(buf);
Victor Stinner76a31a62011-11-04 00:05:13 +01007294 return NULL;
7295 }
7296
7297 if (consumed)
7298 *consumed += converted;
7299
7300 s += converted;
7301 size -= converted;
7302 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007303
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007304 PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
7305 PyMem_Free(buf);
7306 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007307}
7308
Alexander Belopolsky40018472011-02-26 01:02:56 +00007309PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007310PyUnicode_DecodeCodePageStateful(int code_page,
7311 const char *s,
7312 Py_ssize_t size,
7313 const char *errors,
7314 Py_ssize_t *consumed)
7315{
7316 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7317}
7318
7319PyObject *
7320PyUnicode_DecodeMBCSStateful(const char *s,
7321 Py_ssize_t size,
7322 const char *errors,
7323 Py_ssize_t *consumed)
7324{
7325 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7326}
7327
7328PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007329PyUnicode_DecodeMBCS(const char *s,
7330 Py_ssize_t size,
7331 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007332{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007333 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7334}
7335
Victor Stinner3a50e702011-10-18 21:21:00 +02007336static DWORD
7337encode_code_page_flags(UINT code_page, const char *errors)
7338{
7339 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007340 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 }
7342 else if (code_page == CP_UTF7) {
7343 /* CP_UTF7 only supports flags=0 */
7344 return 0;
7345 }
7346 else {
7347 if (errors != NULL && strcmp(errors, "replace") == 0)
7348 return 0;
7349 else
7350 return WC_NO_BEST_FIT_CHARS;
7351 }
7352}
7353
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007354/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 * Encode a Unicode string to a Windows code page into a byte string in strict
7356 * mode.
7357 *
7358 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007359 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007360 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007361static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007362encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007363 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365{
Victor Stinner554f3f02010-06-16 23:33:54 +00007366 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 BOOL *pusedDefaultChar = &usedDefaultChar;
7368 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007369 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007370 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007371 const DWORD flags = encode_code_page_flags(code_page, NULL);
7372 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007373 /* Create a substring so that we can get the UTF-16 representation
7374 of just the slice under consideration. */
7375 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007376
Martin v. Löwis3d325192011-11-04 18:23:06 +01007377 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007378
Victor Stinner3a50e702011-10-18 21:21:00 +02007379 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007380 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007381 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007382 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007383
Victor Stinner2fc507f2011-11-04 20:06:39 +01007384 substring = PyUnicode_Substring(unicode, offset, offset+len);
7385 if (substring == NULL)
7386 return -1;
7387 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7388 if (p == NULL) {
7389 Py_DECREF(substring);
7390 return -1;
7391 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007392 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007393
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007394 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007396 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007397 NULL, 0,
7398 NULL, pusedDefaultChar);
7399 if (outsize <= 0)
7400 goto error;
7401 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007402 if (pusedDefaultChar && *pusedDefaultChar) {
7403 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007404 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007405 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007406
Victor Stinner3a50e702011-10-18 21:21:00 +02007407 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007408 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007410 if (*outbytes == NULL) {
7411 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007412 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007413 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007414 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007415 }
7416 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007417 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 const Py_ssize_t n = PyBytes_Size(*outbytes);
7419 if (outsize > PY_SSIZE_T_MAX - n) {
7420 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007421 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007422 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007424 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7425 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007427 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007429 }
7430
7431 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007433 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 out, outsize,
7435 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007436 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 if (outsize <= 0)
7438 goto error;
7439 if (pusedDefaultChar && *pusedDefaultChar)
7440 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007441 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007442
Victor Stinner3a50e702011-10-18 21:21:00 +02007443error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007444 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7446 return -2;
7447 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007448 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007449}
7450
Victor Stinner3a50e702011-10-18 21:21:00 +02007451/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007452 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 * error handler.
7454 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007455 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 * -1 on other error.
7457 */
7458static int
7459encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007460 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007461 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007462{
Victor Stinner3a50e702011-10-18 21:21:00 +02007463 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007464 Py_ssize_t pos = unicode_offset;
7465 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007466 /* Ideally, we should get reason from FormatMessage. This is the Windows
7467 2000 English version of the message. */
7468 const char *reason = "invalid character";
7469 /* 4=maximum length of a UTF-8 sequence */
7470 char buffer[4];
7471 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7472 Py_ssize_t outsize;
7473 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007474 PyObject *errorHandler = NULL;
7475 PyObject *exc = NULL;
7476 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007477 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007478 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007479 PyObject *rep;
7480 int ret = -1;
7481
7482 assert(insize > 0);
7483
7484 encoding = code_page_name(code_page, &encoding_obj);
7485 if (encoding == NULL)
7486 return -1;
7487
7488 if (errors == NULL || strcmp(errors, "strict") == 0) {
7489 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7490 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007491 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007492 if (exc != NULL) {
7493 PyCodec_StrictErrors(exc);
7494 Py_DECREF(exc);
7495 }
7496 Py_XDECREF(encoding_obj);
7497 return -1;
7498 }
7499
7500 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7501 pusedDefaultChar = &usedDefaultChar;
7502 else
7503 pusedDefaultChar = NULL;
7504
7505 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7506 PyErr_NoMemory();
7507 goto error;
7508 }
7509 outsize = insize * Py_ARRAY_LENGTH(buffer);
7510
7511 if (*outbytes == NULL) {
7512 /* Create string object */
7513 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7514 if (*outbytes == NULL)
7515 goto error;
7516 out = PyBytes_AS_STRING(*outbytes);
7517 }
7518 else {
7519 /* Extend string object */
7520 Py_ssize_t n = PyBytes_Size(*outbytes);
7521 if (n > PY_SSIZE_T_MAX - outsize) {
7522 PyErr_NoMemory();
7523 goto error;
7524 }
7525 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7526 goto error;
7527 out = PyBytes_AS_STRING(*outbytes) + n;
7528 }
7529
7530 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007531 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007532 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007533 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7534 wchar_t chars[2];
7535 int charsize;
7536 if (ch < 0x10000) {
7537 chars[0] = (wchar_t)ch;
7538 charsize = 1;
7539 }
7540 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007541 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7542 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007543 charsize = 2;
7544 }
7545
Victor Stinner3a50e702011-10-18 21:21:00 +02007546 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007547 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007548 buffer, Py_ARRAY_LENGTH(buffer),
7549 NULL, pusedDefaultChar);
7550 if (outsize > 0) {
7551 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7552 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007553 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007554 memcpy(out, buffer, outsize);
7555 out += outsize;
7556 continue;
7557 }
7558 }
7559 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7560 PyErr_SetFromWindowsErr(0);
7561 goto error;
7562 }
7563
Victor Stinner3a50e702011-10-18 21:21:00 +02007564 rep = unicode_encode_call_errorhandler(
7565 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007566 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007567 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007568 if (rep == NULL)
7569 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007570 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007571
7572 if (PyBytes_Check(rep)) {
7573 outsize = PyBytes_GET_SIZE(rep);
7574 if (outsize != 1) {
7575 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7576 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7577 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7578 Py_DECREF(rep);
7579 goto error;
7580 }
7581 out = PyBytes_AS_STRING(*outbytes) + offset;
7582 }
7583 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7584 out += outsize;
7585 }
7586 else {
7587 Py_ssize_t i;
7588 enum PyUnicode_Kind kind;
7589 void *data;
7590
Benjamin Petersonbac79492012-01-14 13:34:47 -05007591 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007592 Py_DECREF(rep);
7593 goto error;
7594 }
7595
7596 outsize = PyUnicode_GET_LENGTH(rep);
7597 if (outsize != 1) {
7598 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7599 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7600 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7601 Py_DECREF(rep);
7602 goto error;
7603 }
7604 out = PyBytes_AS_STRING(*outbytes) + offset;
7605 }
7606 kind = PyUnicode_KIND(rep);
7607 data = PyUnicode_DATA(rep);
7608 for (i=0; i < outsize; i++) {
7609 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7610 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007611 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007612 encoding, unicode,
7613 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007614 "unable to encode error handler result to ASCII");
7615 Py_DECREF(rep);
7616 goto error;
7617 }
7618 *out = (unsigned char)ch;
7619 out++;
7620 }
7621 }
7622 Py_DECREF(rep);
7623 }
7624 /* write a NUL byte */
7625 *out = 0;
7626 outsize = out - PyBytes_AS_STRING(*outbytes);
7627 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7628 if (_PyBytes_Resize(outbytes, outsize) < 0)
7629 goto error;
7630 ret = 0;
7631
7632error:
7633 Py_XDECREF(encoding_obj);
7634 Py_XDECREF(errorHandler);
7635 Py_XDECREF(exc);
7636 return ret;
7637}
7638
Victor Stinner3a50e702011-10-18 21:21:00 +02007639static PyObject *
7640encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007641 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007642 const char *errors)
7643{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007644 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007645 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007646 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007647 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007648
Victor Stinner29dacf22015-01-26 16:41:32 +01007649 if (!PyUnicode_Check(unicode)) {
7650 PyErr_BadArgument();
7651 return NULL;
7652 }
7653
Benjamin Petersonbac79492012-01-14 13:34:47 -05007654 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007655 return NULL;
7656 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007657
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 if (code_page < 0) {
7659 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7660 return NULL;
7661 }
7662
Martin v. Löwis3d325192011-11-04 18:23:06 +01007663 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007664 return PyBytes_FromStringAndSize(NULL, 0);
7665
Victor Stinner7581cef2011-11-03 22:32:33 +01007666 offset = 0;
7667 do
7668 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007669#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007670 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007671 chunks. */
7672 if (len > INT_MAX/2) {
7673 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007674 done = 0;
7675 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007676 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007677#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007678 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007679 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007680 done = 1;
7681 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007682
Victor Stinner76a31a62011-11-04 00:05:13 +01007683 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007684 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007685 errors);
7686 if (ret == -2)
7687 ret = encode_code_page_errors(code_page, &outbytes,
7688 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007689 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007690 if (ret < 0) {
7691 Py_XDECREF(outbytes);
7692 return NULL;
7693 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007694
Victor Stinner7581cef2011-11-03 22:32:33 +01007695 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007696 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007697 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007698
Victor Stinner3a50e702011-10-18 21:21:00 +02007699 return outbytes;
7700}
7701
7702PyObject *
7703PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7704 Py_ssize_t size,
7705 const char *errors)
7706{
Victor Stinner7581cef2011-11-03 22:32:33 +01007707 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007708 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007709 if (unicode == NULL)
7710 return NULL;
7711 res = encode_code_page(CP_ACP, unicode, errors);
7712 Py_DECREF(unicode);
7713 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007714}
7715
7716PyObject *
7717PyUnicode_EncodeCodePage(int code_page,
7718 PyObject *unicode,
7719 const char *errors)
7720{
Victor Stinner7581cef2011-11-03 22:32:33 +01007721 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007722}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007723
Alexander Belopolsky40018472011-02-26 01:02:56 +00007724PyObject *
7725PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007726{
Victor Stinner7581cef2011-11-03 22:32:33 +01007727 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007728}
7729
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007730#undef NEED_RETRY
7731
Steve Dowercc16be82016-09-08 10:35:16 -07007732#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007733
Guido van Rossumd57fd912000-03-10 22:53:23 +00007734/* --- Character Mapping Codec -------------------------------------------- */
7735
Victor Stinnerfb161b12013-04-18 01:44:27 +02007736static int
7737charmap_decode_string(const char *s,
7738 Py_ssize_t size,
7739 PyObject *mapping,
7740 const char *errors,
7741 _PyUnicodeWriter *writer)
7742{
7743 const char *starts = s;
7744 const char *e;
7745 Py_ssize_t startinpos, endinpos;
7746 PyObject *errorHandler = NULL, *exc = NULL;
7747 Py_ssize_t maplen;
7748 enum PyUnicode_Kind mapkind;
7749 void *mapdata;
7750 Py_UCS4 x;
7751 unsigned char ch;
7752
7753 if (PyUnicode_READY(mapping) == -1)
7754 return -1;
7755
7756 maplen = PyUnicode_GET_LENGTH(mapping);
7757 mapdata = PyUnicode_DATA(mapping);
7758 mapkind = PyUnicode_KIND(mapping);
7759
7760 e = s + size;
7761
7762 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7763 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7764 * is disabled in encoding aliases, latin1 is preferred because
7765 * its implementation is faster. */
7766 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7767 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7768 Py_UCS4 maxchar = writer->maxchar;
7769
7770 assert (writer->kind == PyUnicode_1BYTE_KIND);
7771 while (s < e) {
7772 ch = *s;
7773 x = mapdata_ucs1[ch];
7774 if (x > maxchar) {
7775 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7776 goto onError;
7777 maxchar = writer->maxchar;
7778 outdata = (Py_UCS1 *)writer->data;
7779 }
7780 outdata[writer->pos] = x;
7781 writer->pos++;
7782 ++s;
7783 }
7784 return 0;
7785 }
7786
7787 while (s < e) {
7788 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7789 enum PyUnicode_Kind outkind = writer->kind;
7790 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7791 if (outkind == PyUnicode_1BYTE_KIND) {
7792 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7793 Py_UCS4 maxchar = writer->maxchar;
7794 while (s < e) {
7795 ch = *s;
7796 x = mapdata_ucs2[ch];
7797 if (x > maxchar)
7798 goto Error;
7799 outdata[writer->pos] = x;
7800 writer->pos++;
7801 ++s;
7802 }
7803 break;
7804 }
7805 else if (outkind == PyUnicode_2BYTE_KIND) {
7806 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7807 while (s < e) {
7808 ch = *s;
7809 x = mapdata_ucs2[ch];
7810 if (x == 0xFFFE)
7811 goto Error;
7812 outdata[writer->pos] = x;
7813 writer->pos++;
7814 ++s;
7815 }
7816 break;
7817 }
7818 }
7819 ch = *s;
7820
7821 if (ch < maplen)
7822 x = PyUnicode_READ(mapkind, mapdata, ch);
7823 else
7824 x = 0xfffe; /* invalid value */
7825Error:
7826 if (x == 0xfffe)
7827 {
7828 /* undefined mapping */
7829 startinpos = s-starts;
7830 endinpos = startinpos+1;
7831 if (unicode_decode_call_errorhandler_writer(
7832 errors, &errorHandler,
7833 "charmap", "character maps to <undefined>",
7834 &starts, &e, &startinpos, &endinpos, &exc, &s,
7835 writer)) {
7836 goto onError;
7837 }
7838 continue;
7839 }
7840
7841 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7842 goto onError;
7843 ++s;
7844 }
7845 Py_XDECREF(errorHandler);
7846 Py_XDECREF(exc);
7847 return 0;
7848
7849onError:
7850 Py_XDECREF(errorHandler);
7851 Py_XDECREF(exc);
7852 return -1;
7853}
7854
7855static int
7856charmap_decode_mapping(const char *s,
7857 Py_ssize_t size,
7858 PyObject *mapping,
7859 const char *errors,
7860 _PyUnicodeWriter *writer)
7861{
7862 const char *starts = s;
7863 const char *e;
7864 Py_ssize_t startinpos, endinpos;
7865 PyObject *errorHandler = NULL, *exc = NULL;
7866 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007867 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007868
7869 e = s + size;
7870
7871 while (s < e) {
7872 ch = *s;
7873
7874 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7875 key = PyLong_FromLong((long)ch);
7876 if (key == NULL)
7877 goto onError;
7878
7879 item = PyObject_GetItem(mapping, key);
7880 Py_DECREF(key);
7881 if (item == NULL) {
7882 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7883 /* No mapping found means: mapping is undefined. */
7884 PyErr_Clear();
7885 goto Undefined;
7886 } else
7887 goto onError;
7888 }
7889
7890 /* Apply mapping */
7891 if (item == Py_None)
7892 goto Undefined;
7893 if (PyLong_Check(item)) {
7894 long value = PyLong_AS_LONG(item);
7895 if (value == 0xFFFE)
7896 goto Undefined;
7897 if (value < 0 || value > MAX_UNICODE) {
7898 PyErr_Format(PyExc_TypeError,
7899 "character mapping must be in range(0x%lx)",
7900 (unsigned long)MAX_UNICODE + 1);
7901 goto onError;
7902 }
7903
7904 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7905 goto onError;
7906 }
7907 else if (PyUnicode_Check(item)) {
7908 if (PyUnicode_READY(item) == -1)
7909 goto onError;
7910 if (PyUnicode_GET_LENGTH(item) == 1) {
7911 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7912 if (value == 0xFFFE)
7913 goto Undefined;
7914 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7915 goto onError;
7916 }
7917 else {
7918 writer->overallocate = 1;
7919 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7920 goto onError;
7921 }
7922 }
7923 else {
7924 /* wrong return value */
7925 PyErr_SetString(PyExc_TypeError,
7926 "character mapping must return integer, None or str");
7927 goto onError;
7928 }
7929 Py_CLEAR(item);
7930 ++s;
7931 continue;
7932
7933Undefined:
7934 /* undefined mapping */
7935 Py_CLEAR(item);
7936 startinpos = s-starts;
7937 endinpos = startinpos+1;
7938 if (unicode_decode_call_errorhandler_writer(
7939 errors, &errorHandler,
7940 "charmap", "character maps to <undefined>",
7941 &starts, &e, &startinpos, &endinpos, &exc, &s,
7942 writer)) {
7943 goto onError;
7944 }
7945 }
7946 Py_XDECREF(errorHandler);
7947 Py_XDECREF(exc);
7948 return 0;
7949
7950onError:
7951 Py_XDECREF(item);
7952 Py_XDECREF(errorHandler);
7953 Py_XDECREF(exc);
7954 return -1;
7955}
7956
Alexander Belopolsky40018472011-02-26 01:02:56 +00007957PyObject *
7958PyUnicode_DecodeCharmap(const char *s,
7959 Py_ssize_t size,
7960 PyObject *mapping,
7961 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007962{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007963 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007964
Guido van Rossumd57fd912000-03-10 22:53:23 +00007965 /* Default to Latin-1 */
7966 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007967 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007968
Guido van Rossumd57fd912000-03-10 22:53:23 +00007969 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007970 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007971 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007972 writer.min_length = size;
7973 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007974 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007975
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007976 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007977 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7978 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007979 }
7980 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007981 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7982 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007983 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007984 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007985
Benjamin Peterson29060642009-01-31 22:14:21 +00007986 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007987 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007988 return NULL;
7989}
7990
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007991/* Charmap encoding: the lookup table */
7992
Alexander Belopolsky40018472011-02-26 01:02:56 +00007993struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007994 PyObject_HEAD
7995 unsigned char level1[32];
7996 int count2, count3;
7997 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007998};
7999
8000static PyObject*
8001encoding_map_size(PyObject *obj, PyObject* args)
8002{
8003 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008004 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008005 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008006}
8007
8008static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008009 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 PyDoc_STR("Return the size (in bytes) of this object") },
8011 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012};
8013
8014static void
8015encoding_map_dealloc(PyObject* o)
8016{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008017 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008018}
8019
8020static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008021 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008022 "EncodingMap", /*tp_name*/
8023 sizeof(struct encoding_map), /*tp_basicsize*/
8024 0, /*tp_itemsize*/
8025 /* methods */
8026 encoding_map_dealloc, /*tp_dealloc*/
8027 0, /*tp_print*/
8028 0, /*tp_getattr*/
8029 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008030 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008031 0, /*tp_repr*/
8032 0, /*tp_as_number*/
8033 0, /*tp_as_sequence*/
8034 0, /*tp_as_mapping*/
8035 0, /*tp_hash*/
8036 0, /*tp_call*/
8037 0, /*tp_str*/
8038 0, /*tp_getattro*/
8039 0, /*tp_setattro*/
8040 0, /*tp_as_buffer*/
8041 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8042 0, /*tp_doc*/
8043 0, /*tp_traverse*/
8044 0, /*tp_clear*/
8045 0, /*tp_richcompare*/
8046 0, /*tp_weaklistoffset*/
8047 0, /*tp_iter*/
8048 0, /*tp_iternext*/
8049 encoding_map_methods, /*tp_methods*/
8050 0, /*tp_members*/
8051 0, /*tp_getset*/
8052 0, /*tp_base*/
8053 0, /*tp_dict*/
8054 0, /*tp_descr_get*/
8055 0, /*tp_descr_set*/
8056 0, /*tp_dictoffset*/
8057 0, /*tp_init*/
8058 0, /*tp_alloc*/
8059 0, /*tp_new*/
8060 0, /*tp_free*/
8061 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008062};
8063
8064PyObject*
8065PyUnicode_BuildEncodingMap(PyObject* string)
8066{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008067 PyObject *result;
8068 struct encoding_map *mresult;
8069 int i;
8070 int need_dict = 0;
8071 unsigned char level1[32];
8072 unsigned char level2[512];
8073 unsigned char *mlevel1, *mlevel2, *mlevel3;
8074 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008075 int kind;
8076 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008077 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008078 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008079
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008080 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008081 PyErr_BadArgument();
8082 return NULL;
8083 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008084 kind = PyUnicode_KIND(string);
8085 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008086 length = PyUnicode_GET_LENGTH(string);
8087 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088 memset(level1, 0xFF, sizeof level1);
8089 memset(level2, 0xFF, sizeof level2);
8090
8091 /* If there isn't a one-to-one mapping of NULL to \0,
8092 or if there are non-BMP characters, we need to use
8093 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008094 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008095 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008096 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008097 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008098 ch = PyUnicode_READ(kind, data, i);
8099 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100 need_dict = 1;
8101 break;
8102 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008103 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008104 /* unmapped character */
8105 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008106 l1 = ch >> 11;
8107 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108 if (level1[l1] == 0xFF)
8109 level1[l1] = count2++;
8110 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008111 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008112 }
8113
8114 if (count2 >= 0xFF || count3 >= 0xFF)
8115 need_dict = 1;
8116
8117 if (need_dict) {
8118 PyObject *result = PyDict_New();
8119 PyObject *key, *value;
8120 if (!result)
8121 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008122 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008123 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008124 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008125 if (!key || !value)
8126 goto failed1;
8127 if (PyDict_SetItem(result, key, value) == -1)
8128 goto failed1;
8129 Py_DECREF(key);
8130 Py_DECREF(value);
8131 }
8132 return result;
8133 failed1:
8134 Py_XDECREF(key);
8135 Py_XDECREF(value);
8136 Py_DECREF(result);
8137 return NULL;
8138 }
8139
8140 /* Create a three-level trie */
8141 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8142 16*count2 + 128*count3 - 1);
8143 if (!result)
8144 return PyErr_NoMemory();
8145 PyObject_Init(result, &EncodingMapType);
8146 mresult = (struct encoding_map*)result;
8147 mresult->count2 = count2;
8148 mresult->count3 = count3;
8149 mlevel1 = mresult->level1;
8150 mlevel2 = mresult->level23;
8151 mlevel3 = mresult->level23 + 16*count2;
8152 memcpy(mlevel1, level1, 32);
8153 memset(mlevel2, 0xFF, 16*count2);
8154 memset(mlevel3, 0, 128*count3);
8155 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008156 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008157 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008158 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8159 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008160 /* unmapped character */
8161 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008162 o1 = ch>>11;
8163 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008164 i2 = 16*mlevel1[o1] + o2;
8165 if (mlevel2[i2] == 0xFF)
8166 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008167 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008168 i3 = 128*mlevel2[i2] + o3;
8169 mlevel3[i3] = i;
8170 }
8171 return result;
8172}
8173
8174static int
Victor Stinner22168992011-11-20 17:09:18 +01008175encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008176{
8177 struct encoding_map *map = (struct encoding_map*)mapping;
8178 int l1 = c>>11;
8179 int l2 = (c>>7) & 0xF;
8180 int l3 = c & 0x7F;
8181 int i;
8182
Victor Stinner22168992011-11-20 17:09:18 +01008183 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008184 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008185 if (c == 0)
8186 return 0;
8187 /* level 1*/
8188 i = map->level1[l1];
8189 if (i == 0xFF) {
8190 return -1;
8191 }
8192 /* level 2*/
8193 i = map->level23[16*i+l2];
8194 if (i == 0xFF) {
8195 return -1;
8196 }
8197 /* level 3 */
8198 i = map->level23[16*map->count2 + 128*i + l3];
8199 if (i == 0) {
8200 return -1;
8201 }
8202 return i;
8203}
8204
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205/* Lookup the character ch in the mapping. If the character
8206 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008207 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008208static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008209charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008210{
Christian Heimes217cfd12007-12-02 14:31:20 +00008211 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008212 PyObject *x;
8213
8214 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216 x = PyObject_GetItem(mapping, w);
8217 Py_DECREF(w);
8218 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008219 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8220 /* No mapping found means: mapping is undefined. */
8221 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008222 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008223 } else
8224 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008225 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008226 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008227 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008228 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 long value = PyLong_AS_LONG(x);
8230 if (value < 0 || value > 255) {
8231 PyErr_SetString(PyExc_TypeError,
8232 "character mapping must be in range(256)");
8233 Py_DECREF(x);
8234 return NULL;
8235 }
8236 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008237 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008238 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 /* wrong return value */
8242 PyErr_Format(PyExc_TypeError,
8243 "character mapping must return integer, bytes or None, not %.400s",
8244 x->ob_type->tp_name);
8245 Py_DECREF(x);
8246 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008247 }
8248}
8249
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008250static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008251charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008252{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008253 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8254 /* exponentially overallocate to minimize reallocations */
8255 if (requiredsize < 2*outsize)
8256 requiredsize = 2*outsize;
8257 if (_PyBytes_Resize(outobj, requiredsize))
8258 return -1;
8259 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008260}
8261
Benjamin Peterson14339b62009-01-31 16:36:08 +00008262typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008264} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008266 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008267 space is available. Return a new reference to the object that
8268 was put in the output buffer, or Py_None, if the mapping was undefined
8269 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008270 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008271static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008272charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008273 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008274{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008275 PyObject *rep;
8276 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008277 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008278
Christian Heimes90aa7642007-12-19 02:45:37 +00008279 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008280 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008281 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008282 if (res == -1)
8283 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008284 if (outsize<requiredsize)
8285 if (charmapencode_resize(outobj, outpos, requiredsize))
8286 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008287 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 outstart[(*outpos)++] = (char)res;
8289 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008290 }
8291
8292 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008293 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008294 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008295 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008296 Py_DECREF(rep);
8297 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008298 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 if (PyLong_Check(rep)) {
8300 Py_ssize_t requiredsize = *outpos+1;
8301 if (outsize<requiredsize)
8302 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8303 Py_DECREF(rep);
8304 return enc_EXCEPTION;
8305 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008306 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008307 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008308 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 else {
8310 const char *repchars = PyBytes_AS_STRING(rep);
8311 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8312 Py_ssize_t requiredsize = *outpos+repsize;
8313 if (outsize<requiredsize)
8314 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8315 Py_DECREF(rep);
8316 return enc_EXCEPTION;
8317 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008318 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 memcpy(outstart + *outpos, repchars, repsize);
8320 *outpos += repsize;
8321 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008323 Py_DECREF(rep);
8324 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325}
8326
8327/* handle an error in PyUnicode_EncodeCharmap
8328 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008329static int
8330charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008331 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008332 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008333 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008334 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335{
8336 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008337 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008338 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008339 enum PyUnicode_Kind kind;
8340 void *data;
8341 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008343 Py_ssize_t collstartpos = *inpos;
8344 Py_ssize_t collendpos = *inpos+1;
8345 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008346 const char *encoding = "charmap";
8347 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008348 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008349 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008350 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351
Benjamin Petersonbac79492012-01-14 13:34:47 -05008352 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008353 return -1;
8354 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355 /* find all unencodable characters */
8356 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008357 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008358 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008359 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008360 val = encoding_map_lookup(ch, mapping);
8361 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 break;
8363 ++collendpos;
8364 continue;
8365 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008366
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008367 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8368 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 if (rep==NULL)
8370 return -1;
8371 else if (rep!=Py_None) {
8372 Py_DECREF(rep);
8373 break;
8374 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008375 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008377 }
8378 /* cache callback name lookup
8379 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008380 if (*error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02008381 *error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02008382
8383 switch (*error_handler) {
8384 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008385 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008386 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008387
8388 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008389 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 x = charmapencode_output('?', mapping, res, respos);
8391 if (x==enc_EXCEPTION) {
8392 return -1;
8393 }
8394 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008395 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008396 return -1;
8397 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008398 }
8399 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008400 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008401 *inpos = collendpos;
8402 break;
Victor Stinner50149202015-09-22 00:26:54 +02008403
8404 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008405 /* generate replacement (temporarily (mis)uses p) */
8406 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 char buffer[2+29+1+1];
8408 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008409 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 for (cp = buffer; *cp; ++cp) {
8411 x = charmapencode_output(*cp, mapping, res, respos);
8412 if (x==enc_EXCEPTION)
8413 return -1;
8414 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008415 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 return -1;
8417 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008418 }
8419 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008420 *inpos = collendpos;
8421 break;
Victor Stinner50149202015-09-22 00:26:54 +02008422
Benjamin Peterson14339b62009-01-31 16:36:08 +00008423 default:
Victor Stinner50149202015-09-22 00:26:54 +02008424 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008425 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008427 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008428 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008429 if (PyBytes_Check(repunicode)) {
8430 /* Directly copy bytes result to output. */
8431 Py_ssize_t outsize = PyBytes_Size(*res);
8432 Py_ssize_t requiredsize;
8433 repsize = PyBytes_Size(repunicode);
8434 requiredsize = *respos + repsize;
8435 if (requiredsize > outsize)
8436 /* Make room for all additional bytes. */
8437 if (charmapencode_resize(res, respos, requiredsize)) {
8438 Py_DECREF(repunicode);
8439 return -1;
8440 }
8441 memcpy(PyBytes_AsString(*res) + *respos,
8442 PyBytes_AsString(repunicode), repsize);
8443 *respos += repsize;
8444 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008445 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008446 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008447 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008448 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008449 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008450 Py_DECREF(repunicode);
8451 return -1;
8452 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008453 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008454 data = PyUnicode_DATA(repunicode);
8455 kind = PyUnicode_KIND(repunicode);
8456 for (index = 0; index < repsize; index++) {
8457 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8458 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008460 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008461 return -1;
8462 }
8463 else if (x==enc_FAILED) {
8464 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008465 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 return -1;
8467 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008468 }
8469 *inpos = newpos;
8470 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 }
8472 return 0;
8473}
8474
Alexander Belopolsky40018472011-02-26 01:02:56 +00008475PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008476_PyUnicode_EncodeCharmap(PyObject *unicode,
8477 PyObject *mapping,
8478 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008479{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480 /* output object */
8481 PyObject *res = NULL;
8482 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008483 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008484 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008485 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008486 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008487 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008489 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008490 void *data;
8491 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008492
Benjamin Petersonbac79492012-01-14 13:34:47 -05008493 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008494 return NULL;
8495 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008496 data = PyUnicode_DATA(unicode);
8497 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008498
Guido van Rossumd57fd912000-03-10 22:53:23 +00008499 /* Default to Latin-1 */
8500 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008501 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008502
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503 /* allocate enough for a simple encoding without
8504 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008505 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506 if (res == NULL)
8507 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008508 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008510
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008512 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008514 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 if (x==enc_EXCEPTION) /* error */
8516 goto onError;
8517 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008518 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008520 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008521 &res, &respos)) {
8522 goto onError;
8523 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008524 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 else
8526 /* done with this character => adjust input position */
8527 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008528 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008529
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008530 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008531 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008532 if (_PyBytes_Resize(&res, respos) < 0)
8533 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008534
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008535 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008536 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 return res;
8538
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008540 Py_XDECREF(res);
8541 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008542 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008543 return NULL;
8544}
8545
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008546/* Deprecated */
8547PyObject *
8548PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8549 Py_ssize_t size,
8550 PyObject *mapping,
8551 const char *errors)
8552{
8553 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008554 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008555 if (unicode == NULL)
8556 return NULL;
8557 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8558 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008559 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008560}
8561
Alexander Belopolsky40018472011-02-26 01:02:56 +00008562PyObject *
8563PyUnicode_AsCharmapString(PyObject *unicode,
8564 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008565{
8566 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008567 PyErr_BadArgument();
8568 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008570 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008571}
8572
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008573/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008574static void
8575make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008576 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008577 Py_ssize_t startpos, Py_ssize_t endpos,
8578 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581 *exceptionObject = _PyUnicodeTranslateError_Create(
8582 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008583 }
8584 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8586 goto onError;
8587 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8588 goto onError;
8589 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8590 goto onError;
8591 return;
8592 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008593 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594 }
8595}
8596
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597/* error handling callback helper:
8598 build arguments, call the callback and check the arguments,
8599 put the result into newpos and return the replacement string, which
8600 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008601static PyObject *
8602unicode_translate_call_errorhandler(const char *errors,
8603 PyObject **errorHandler,
8604 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008606 Py_ssize_t startpos, Py_ssize_t endpos,
8607 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008609 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008611 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008612 PyObject *restuple;
8613 PyObject *resunicode;
8614
8615 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008618 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008619 }
8620
8621 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008622 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008625
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008626 restuple = PyObject_CallFunctionObjArgs(
8627 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008630 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008631 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 Py_DECREF(restuple);
8633 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008635 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 &resunicode, &i_newpos)) {
8637 Py_DECREF(restuple);
8638 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008640 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008641 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008642 else
8643 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008644 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008645 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 Py_DECREF(restuple);
8647 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008648 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008649 Py_INCREF(resunicode);
8650 Py_DECREF(restuple);
8651 return resunicode;
8652}
8653
8654/* Lookup the character ch in the mapping and put the result in result,
8655 which must be decrefed by the caller.
8656 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008657static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008658charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659{
Christian Heimes217cfd12007-12-02 14:31:20 +00008660 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661 PyObject *x;
8662
8663 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 x = PyObject_GetItem(mapping, w);
8666 Py_DECREF(w);
8667 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8669 /* No mapping found means: use 1:1 mapping. */
8670 PyErr_Clear();
8671 *result = NULL;
8672 return 0;
8673 } else
8674 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675 }
8676 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 *result = x;
8678 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008680 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008681 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008682 if (value < 0 || value > MAX_UNICODE) {
8683 PyErr_Format(PyExc_ValueError,
8684 "character mapping must be in range(0x%x)",
8685 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 Py_DECREF(x);
8687 return -1;
8688 }
8689 *result = x;
8690 return 0;
8691 }
8692 else if (PyUnicode_Check(x)) {
8693 *result = x;
8694 return 0;
8695 }
8696 else {
8697 /* wrong return value */
8698 PyErr_SetString(PyExc_TypeError,
8699 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008700 Py_DECREF(x);
8701 return -1;
8702 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008703}
Victor Stinner1194ea02014-04-04 19:37:40 +02008704
8705/* lookup the character, write the result into the writer.
8706 Return 1 if the result was written into the writer, return 0 if the mapping
8707 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008708static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008709charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8710 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008711{
Victor Stinner1194ea02014-04-04 19:37:40 +02008712 PyObject *item;
8713
8714 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008716
8717 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008719 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008720 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008722 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008723 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008724
8725 if (item == Py_None) {
8726 Py_DECREF(item);
8727 return 0;
8728 }
8729
8730 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008731 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8732 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8733 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008734 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8735 Py_DECREF(item);
8736 return -1;
8737 }
8738 Py_DECREF(item);
8739 return 1;
8740 }
8741
8742 if (!PyUnicode_Check(item)) {
8743 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008745 }
8746
8747 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8748 Py_DECREF(item);
8749 return -1;
8750 }
8751
8752 Py_DECREF(item);
8753 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008754}
8755
Victor Stinner89a76ab2014-04-05 11:44:04 +02008756static int
8757unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8758 Py_UCS1 *translate)
8759{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008760 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008761 int ret = 0;
8762
Victor Stinner89a76ab2014-04-05 11:44:04 +02008763 if (charmaptranslate_lookup(ch, mapping, &item)) {
8764 return -1;
8765 }
8766
8767 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008768 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008769 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008770 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008771 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008772 /* not found => default to 1:1 mapping */
8773 translate[ch] = ch;
8774 return 1;
8775 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008776 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008777 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008778 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8779 used it */
8780 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008781 /* invalid character or character outside ASCII:
8782 skip the fast translate */
8783 goto exit;
8784 }
8785 translate[ch] = (Py_UCS1)replace;
8786 }
8787 else if (PyUnicode_Check(item)) {
8788 Py_UCS4 replace;
8789
8790 if (PyUnicode_READY(item) == -1) {
8791 Py_DECREF(item);
8792 return -1;
8793 }
8794 if (PyUnicode_GET_LENGTH(item) != 1)
8795 goto exit;
8796
8797 replace = PyUnicode_READ_CHAR(item, 0);
8798 if (replace > 127)
8799 goto exit;
8800 translate[ch] = (Py_UCS1)replace;
8801 }
8802 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008803 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008804 goto exit;
8805 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008806 ret = 1;
8807
Benjamin Peterson1365de72014-04-07 20:15:41 -04008808 exit:
8809 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008810 return ret;
8811}
8812
8813/* Fast path for ascii => ascii translation. Return 1 if the whole string
8814 was translated into writer, return 0 if the input string was partially
8815 translated into writer, raise an exception and return -1 on error. */
8816static int
8817unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008818 _PyUnicodeWriter *writer, int ignore,
8819 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008820{
Victor Stinner872b2912014-04-05 14:27:07 +02008821 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008822 Py_ssize_t len;
8823 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008824 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008825
Victor Stinner89a76ab2014-04-05 11:44:04 +02008826 len = PyUnicode_GET_LENGTH(input);
8827
Victor Stinner872b2912014-04-05 14:27:07 +02008828 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008829
8830 in = PyUnicode_1BYTE_DATA(input);
8831 end = in + len;
8832
8833 assert(PyUnicode_IS_ASCII(writer->buffer));
8834 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8835 out = PyUnicode_1BYTE_DATA(writer->buffer);
8836
Victor Stinner872b2912014-04-05 14:27:07 +02008837 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008838 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008839 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008840 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008841 int translate = unicode_fast_translate_lookup(mapping, ch,
8842 ascii_table);
8843 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008844 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008845 if (translate == 0)
8846 goto exit;
8847 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008848 }
Victor Stinner872b2912014-04-05 14:27:07 +02008849 if (ch2 == 0xfe) {
8850 if (ignore)
8851 continue;
8852 goto exit;
8853 }
8854 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008855 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008856 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008857 }
Victor Stinner872b2912014-04-05 14:27:07 +02008858 res = 1;
8859
8860exit:
8861 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008862 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008863 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008864}
8865
Victor Stinner3222da22015-10-01 22:07:32 +02008866static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008867_PyUnicode_TranslateCharmap(PyObject *input,
8868 PyObject *mapping,
8869 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008870{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008872 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008873 Py_ssize_t size, i;
8874 int kind;
8875 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008876 _PyUnicodeWriter writer;
8877 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008878 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008879 PyObject *errorHandler = NULL;
8880 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008881 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008882 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008883
Guido van Rossumd57fd912000-03-10 22:53:23 +00008884 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008885 PyErr_BadArgument();
8886 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008887 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008888
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008889 if (PyUnicode_READY(input) == -1)
8890 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008891 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008892 kind = PyUnicode_KIND(input);
8893 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008894
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008895 if (size == 0)
8896 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008898 /* allocate enough for a simple 1:1 translation without
8899 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008900 _PyUnicodeWriter_Init(&writer);
8901 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008902 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008903
Victor Stinner872b2912014-04-05 14:27:07 +02008904 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8905
Victor Stinner33798672016-03-01 21:59:58 +01008906 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008907 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008908 if (PyUnicode_IS_ASCII(input)) {
8909 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8910 if (res < 0) {
8911 _PyUnicodeWriter_Dealloc(&writer);
8912 return NULL;
8913 }
8914 if (res == 1)
8915 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008916 }
Victor Stinner33798672016-03-01 21:59:58 +01008917 else {
8918 i = 0;
8919 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008920
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008921 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008922 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008923 int translate;
8924 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8925 Py_ssize_t newpos;
8926 /* startpos for collecting untranslatable chars */
8927 Py_ssize_t collstart;
8928 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008929 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008930
Victor Stinner1194ea02014-04-04 19:37:40 +02008931 ch = PyUnicode_READ(kind, data, i);
8932 translate = charmaptranslate_output(ch, mapping, &writer);
8933 if (translate < 0)
8934 goto onError;
8935
8936 if (translate != 0) {
8937 /* it worked => adjust input pointer */
8938 ++i;
8939 continue;
8940 }
8941
8942 /* untranslatable character */
8943 collstart = i;
8944 collend = i+1;
8945
8946 /* find all untranslatable characters */
8947 while (collend < size) {
8948 PyObject *x;
8949 ch = PyUnicode_READ(kind, data, collend);
8950 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008951 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008952 Py_XDECREF(x);
8953 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008954 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008955 ++collend;
8956 }
8957
8958 if (ignore) {
8959 i = collend;
8960 }
8961 else {
8962 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8963 reason, input, &exc,
8964 collstart, collend, &newpos);
8965 if (repunicode == NULL)
8966 goto onError;
8967 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008968 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008969 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008970 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008971 Py_DECREF(repunicode);
8972 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008973 }
8974 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008975 Py_XDECREF(exc);
8976 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008977 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008978
Benjamin Peterson29060642009-01-31 22:14:21 +00008979 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008980 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008981 Py_XDECREF(exc);
8982 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008983 return NULL;
8984}
8985
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008986/* Deprecated. Use PyUnicode_Translate instead. */
8987PyObject *
8988PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8989 Py_ssize_t size,
8990 PyObject *mapping,
8991 const char *errors)
8992{
Christian Heimes5f520f42012-09-11 14:03:25 +02008993 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008994 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008995 if (!unicode)
8996 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02008997 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8998 Py_DECREF(unicode);
8999 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000}
9001
Alexander Belopolsky40018472011-02-26 01:02:56 +00009002PyObject *
9003PyUnicode_Translate(PyObject *str,
9004 PyObject *mapping,
9005 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009006{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009007 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009008 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009009 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009010}
Tim Petersced69f82003-09-16 20:30:58 +00009011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012PyObject *
9013_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9014{
9015 if (!PyUnicode_Check(unicode)) {
9016 PyErr_BadInternalCall();
9017 return NULL;
9018 }
9019 if (PyUnicode_READY(unicode) == -1)
9020 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009021 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009022 /* If the string is already ASCII, just return the same string */
9023 Py_INCREF(unicode);
9024 return unicode;
9025 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009026
9027 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9028 PyObject *result = PyUnicode_New(len, 127);
9029 if (result == NULL) {
9030 return NULL;
9031 }
9032
9033 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9034 int kind = PyUnicode_KIND(unicode);
9035 const void *data = PyUnicode_DATA(unicode);
9036 Py_ssize_t i;
9037 for (i = 0; i < len; ++i) {
9038 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9039 if (ch < 127) {
9040 out[i] = ch;
9041 }
9042 else if (Py_UNICODE_ISSPACE(ch)) {
9043 out[i] = ' ';
9044 }
9045 else {
9046 int decimal = Py_UNICODE_TODECIMAL(ch);
9047 if (decimal < 0) {
9048 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009049 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009050 _PyUnicode_LENGTH(result) = i + 1;
9051 break;
9052 }
9053 out[i] = '0' + decimal;
9054 }
9055 }
9056
INADA Naoki16dfca42018-07-14 12:06:43 +09009057 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009058 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009059}
9060
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009061PyObject *
9062PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9063 Py_ssize_t length)
9064{
Victor Stinnerf0124502011-11-21 23:12:56 +01009065 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009066 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009067 Py_UCS4 maxchar;
9068 enum PyUnicode_Kind kind;
9069 void *data;
9070
Victor Stinner99d7ad02012-02-22 13:37:39 +01009071 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009072 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009073 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009074 if (ch > 127) {
9075 int decimal = Py_UNICODE_TODECIMAL(ch);
9076 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009077 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009078 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009079 }
9080 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009081
9082 /* Copy to a new string */
9083 decimal = PyUnicode_New(length, maxchar);
9084 if (decimal == NULL)
9085 return decimal;
9086 kind = PyUnicode_KIND(decimal);
9087 data = PyUnicode_DATA(decimal);
9088 /* Iterate over code points */
9089 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009090 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009091 if (ch > 127) {
9092 int decimal = Py_UNICODE_TODECIMAL(ch);
9093 if (decimal >= 0)
9094 ch = '0' + decimal;
9095 }
9096 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009098 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009099}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009100/* --- Decimal Encoder ---------------------------------------------------- */
9101
Alexander Belopolsky40018472011-02-26 01:02:56 +00009102int
9103PyUnicode_EncodeDecimal(Py_UNICODE *s,
9104 Py_ssize_t length,
9105 char *output,
9106 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009107{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009108 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009109 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009110 enum PyUnicode_Kind kind;
9111 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009112
9113 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009114 PyErr_BadArgument();
9115 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009116 }
9117
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009118 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009119 if (unicode == NULL)
9120 return -1;
9121
Victor Stinner42bf7752011-11-21 22:52:58 +01009122 kind = PyUnicode_KIND(unicode);
9123 data = PyUnicode_DATA(unicode);
9124
Victor Stinnerb84d7232011-11-22 01:50:07 +01009125 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009126 PyObject *exc;
9127 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009128 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009129 Py_ssize_t startpos;
9130
9131 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009132
Benjamin Peterson29060642009-01-31 22:14:21 +00009133 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009134 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009135 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009136 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009137 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009138 decimal = Py_UNICODE_TODECIMAL(ch);
9139 if (decimal >= 0) {
9140 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009141 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 continue;
9143 }
9144 if (0 < ch && ch < 256) {
9145 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009146 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 continue;
9148 }
Victor Stinner6345be92011-11-25 20:09:01 +01009149
Victor Stinner42bf7752011-11-21 22:52:58 +01009150 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009151 exc = NULL;
9152 raise_encode_exception(&exc, "decimal", unicode,
9153 startpos, startpos+1,
9154 "invalid decimal Unicode string");
9155 Py_XDECREF(exc);
9156 Py_DECREF(unicode);
9157 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009158 }
9159 /* 0-terminate the output string */
9160 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009161 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009162 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009163}
9164
Guido van Rossumd57fd912000-03-10 22:53:23 +00009165/* --- Helpers ------------------------------------------------------------ */
9166
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009167/* helper macro to fixup start/end slice values */
9168#define ADJUST_INDICES(start, end, len) \
9169 if (end > len) \
9170 end = len; \
9171 else if (end < 0) { \
9172 end += len; \
9173 if (end < 0) \
9174 end = 0; \
9175 } \
9176 if (start < 0) { \
9177 start += len; \
9178 if (start < 0) \
9179 start = 0; \
9180 }
9181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009183any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009184 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009185 Py_ssize_t end,
9186 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009187{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009188 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009189 void *buf1, *buf2;
9190 Py_ssize_t len1, len2, result;
9191
9192 kind1 = PyUnicode_KIND(s1);
9193 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009194 if (kind1 < kind2)
9195 return -1;
9196
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197 len1 = PyUnicode_GET_LENGTH(s1);
9198 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009199 ADJUST_INDICES(start, end, len1);
9200 if (end - start < len2)
9201 return -1;
9202
9203 buf1 = PyUnicode_DATA(s1);
9204 buf2 = PyUnicode_DATA(s2);
9205 if (len2 == 1) {
9206 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9207 result = findchar((const char *)buf1 + kind1*start,
9208 kind1, end - start, ch, direction);
9209 if (result == -1)
9210 return -1;
9211 else
9212 return start + result;
9213 }
9214
9215 if (kind2 != kind1) {
9216 buf2 = _PyUnicode_AsKind(s2, kind1);
9217 if (!buf2)
9218 return -2;
9219 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220
Victor Stinner794d5672011-10-10 03:21:36 +02009221 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009222 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009223 case PyUnicode_1BYTE_KIND:
9224 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9225 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9226 else
9227 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9228 break;
9229 case PyUnicode_2BYTE_KIND:
9230 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9231 break;
9232 case PyUnicode_4BYTE_KIND:
9233 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9234 break;
9235 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009236 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009237 }
9238 }
9239 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009240 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009241 case PyUnicode_1BYTE_KIND:
9242 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9243 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9244 else
9245 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9246 break;
9247 case PyUnicode_2BYTE_KIND:
9248 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9249 break;
9250 case PyUnicode_4BYTE_KIND:
9251 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9252 break;
9253 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009254 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009256 }
9257
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009258 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 PyMem_Free(buf2);
9260
9261 return result;
9262}
9263
Victor Stinner59423e32018-11-26 13:40:01 +01009264/* _PyUnicode_InsertThousandsGrouping() helper functions */
9265#include "stringlib/localeutil.h"
9266
9267/**
9268 * InsertThousandsGrouping:
9269 * @writer: Unicode writer.
9270 * @n_buffer: Number of characters in @buffer.
9271 * @digits: Digits we're reading from. If count is non-NULL, this is unused.
9272 * @d_pos: Start of digits string.
9273 * @n_digits: The number of digits in the string, in which we want
9274 * to put the grouping chars.
9275 * @min_width: The minimum width of the digits in the output string.
9276 * Output will be zero-padded on the left to fill.
9277 * @grouping: see definition in localeconv().
9278 * @thousands_sep: see definition in localeconv().
9279 *
9280 * There are 2 modes: counting and filling. If @writer is NULL,
9281 * we are in counting mode, else filling mode.
9282 * If counting, the required buffer size is returned.
9283 * If filling, we know the buffer will be large enough, so we don't
9284 * need to pass in the buffer size.
9285 * Inserts thousand grouping characters (as defined by grouping and
9286 * thousands_sep) into @writer.
9287 *
9288 * Return value: -1 on error, number of characters otherwise.
9289 **/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009290Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009291_PyUnicode_InsertThousandsGrouping(
Victor Stinner59423e32018-11-26 13:40:01 +01009292 _PyUnicodeWriter *writer,
Victor Stinner41a863c2012-02-24 00:37:51 +01009293 Py_ssize_t n_buffer,
Victor Stinner59423e32018-11-26 13:40:01 +01009294 PyObject *digits,
9295 Py_ssize_t d_pos,
9296 Py_ssize_t n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009297 Py_ssize_t min_width,
Victor Stinner59423e32018-11-26 13:40:01 +01009298 const char *grouping,
9299 PyObject *thousands_sep,
Victor Stinner41a863c2012-02-24 00:37:51 +01009300 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301{
Xtreak3f7983a2019-01-07 20:39:14 +05309302 min_width = Py_MAX(0, min_width);
Victor Stinner59423e32018-11-26 13:40:01 +01009303 if (writer) {
9304 assert(digits != NULL);
9305 assert(maxchar == NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009306 }
9307 else {
Victor Stinner59423e32018-11-26 13:40:01 +01009308 assert(digits == NULL);
9309 assert(maxchar != NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009310 }
Victor Stinner59423e32018-11-26 13:40:01 +01009311 assert(0 <= d_pos);
9312 assert(0 <= n_digits);
Victor Stinner59423e32018-11-26 13:40:01 +01009313 assert(grouping != NULL);
9314
9315 if (digits != NULL) {
9316 if (PyUnicode_READY(digits) == -1) {
9317 return -1;
Victor Stinner90f50d42012-02-24 01:44:47 +01009318 }
Victor Stinner59423e32018-11-26 13:40:01 +01009319 }
9320 if (PyUnicode_READY(thousands_sep) == -1) {
9321 return -1;
Victor Stinner41a863c2012-02-24 00:37:51 +01009322 }
9323
Victor Stinner59423e32018-11-26 13:40:01 +01009324 Py_ssize_t count = 0;
9325 Py_ssize_t n_zeros;
9326 int loop_broken = 0;
9327 int use_separator = 0; /* First time through, don't append the
9328 separator. They only go between
9329 groups. */
9330 Py_ssize_t buffer_pos;
9331 Py_ssize_t digits_pos;
9332 Py_ssize_t len;
9333 Py_ssize_t n_chars;
9334 Py_ssize_t remaining = n_digits; /* Number of chars remaining to
9335 be looked at */
9336 /* A generator that returns all of the grouping widths, until it
9337 returns 0. */
9338 GroupGenerator groupgen;
9339 GroupGenerator_init(&groupgen, grouping);
9340 const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9341
9342 /* if digits are not grouped, thousands separator
9343 should be an empty string */
9344 assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
9345
9346 digits_pos = d_pos + n_digits;
9347 if (writer) {
9348 buffer_pos = writer->pos + n_buffer;
9349 assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
9350 assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009351 }
Victor Stinner59423e32018-11-26 13:40:01 +01009352 else {
9353 buffer_pos = n_buffer;
Victor Stinner90f50d42012-02-24 01:44:47 +01009354 }
Victor Stinner59423e32018-11-26 13:40:01 +01009355
9356 if (!writer) {
Victor Stinner41a863c2012-02-24 00:37:51 +01009357 *maxchar = 127;
Victor Stinner41a863c2012-02-24 00:37:51 +01009358 }
Victor Stinner59423e32018-11-26 13:40:01 +01009359
9360 while ((len = GroupGenerator_next(&groupgen)) > 0) {
9361 len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
9362 n_zeros = Py_MAX(0, len - remaining);
9363 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9364
9365 /* Use n_zero zero's and n_chars chars */
9366
9367 /* Count only, don't do anything. */
9368 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9369
9370 /* Copy into the writer. */
9371 InsertThousandsGrouping_fill(writer, &buffer_pos,
9372 digits, &digits_pos,
9373 n_chars, n_zeros,
9374 use_separator ? thousands_sep : NULL,
9375 thousands_sep_len, maxchar);
9376
9377 /* Use a separator next time. */
9378 use_separator = 1;
9379
9380 remaining -= n_chars;
9381 min_width -= len;
9382
9383 if (remaining <= 0 && min_width <= 0) {
9384 loop_broken = 1;
9385 break;
9386 }
9387 min_width -= thousands_sep_len;
9388 }
9389 if (!loop_broken) {
9390 /* We left the loop without using a break statement. */
9391
9392 len = Py_MAX(Py_MAX(remaining, min_width), 1);
9393 n_zeros = Py_MAX(0, len - remaining);
9394 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9395
9396 /* Use n_zero zero's and n_chars chars */
9397 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9398
9399 /* Copy into the writer. */
9400 InsertThousandsGrouping_fill(writer, &buffer_pos,
9401 digits, &digits_pos,
9402 n_chars, n_zeros,
9403 use_separator ? thousands_sep : NULL,
9404 thousands_sep_len, maxchar);
9405 }
9406 return count;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407}
9408
9409
Alexander Belopolsky40018472011-02-26 01:02:56 +00009410Py_ssize_t
9411PyUnicode_Count(PyObject *str,
9412 PyObject *substr,
9413 Py_ssize_t start,
9414 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009415{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009416 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009417 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418 void *buf1 = NULL, *buf2 = NULL;
9419 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009420
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009421 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009422 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009423
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009424 kind1 = PyUnicode_KIND(str);
9425 kind2 = PyUnicode_KIND(substr);
9426 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009427 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009428
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009429 len1 = PyUnicode_GET_LENGTH(str);
9430 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009432 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009433 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009434
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009435 buf1 = PyUnicode_DATA(str);
9436 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009437 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009438 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009439 if (!buf2)
9440 goto onError;
9441 }
9442
9443 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009444 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009445 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009446 result = asciilib_count(
9447 ((Py_UCS1*)buf1) + start, end - start,
9448 buf2, len2, PY_SSIZE_T_MAX
9449 );
9450 else
9451 result = ucs1lib_count(
9452 ((Py_UCS1*)buf1) + start, end - start,
9453 buf2, len2, PY_SSIZE_T_MAX
9454 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 break;
9456 case PyUnicode_2BYTE_KIND:
9457 result = ucs2lib_count(
9458 ((Py_UCS2*)buf1) + start, end - start,
9459 buf2, len2, PY_SSIZE_T_MAX
9460 );
9461 break;
9462 case PyUnicode_4BYTE_KIND:
9463 result = ucs4lib_count(
9464 ((Py_UCS4*)buf1) + start, end - start,
9465 buf2, len2, PY_SSIZE_T_MAX
9466 );
9467 break;
9468 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009469 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009471
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009472 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009473 PyMem_Free(buf2);
9474
Guido van Rossumd57fd912000-03-10 22:53:23 +00009475 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009477 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009478 PyMem_Free(buf2);
9479 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009480}
9481
Alexander Belopolsky40018472011-02-26 01:02:56 +00009482Py_ssize_t
9483PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009484 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009485 Py_ssize_t start,
9486 Py_ssize_t end,
9487 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009488{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009489 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009490 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009491
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009492 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493}
9494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495Py_ssize_t
9496PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9497 Py_ssize_t start, Py_ssize_t end,
9498 int direction)
9499{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009500 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009501 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009502 if (PyUnicode_READY(str) == -1)
9503 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009504 len = PyUnicode_GET_LENGTH(str);
9505 ADJUST_INDICES(start, end, len);
9506 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009507 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009509 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9510 kind, end-start, ch, direction);
9511 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009513 else
9514 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515}
9516
Alexander Belopolsky40018472011-02-26 01:02:56 +00009517static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009518tailmatch(PyObject *self,
9519 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009520 Py_ssize_t start,
9521 Py_ssize_t end,
9522 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009523{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009524 int kind_self;
9525 int kind_sub;
9526 void *data_self;
9527 void *data_sub;
9528 Py_ssize_t offset;
9529 Py_ssize_t i;
9530 Py_ssize_t end_sub;
9531
9532 if (PyUnicode_READY(self) == -1 ||
9533 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009534 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009536 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9537 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009538 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009539 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009540
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009541 if (PyUnicode_GET_LENGTH(substring) == 0)
9542 return 1;
9543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 kind_self = PyUnicode_KIND(self);
9545 data_self = PyUnicode_DATA(self);
9546 kind_sub = PyUnicode_KIND(substring);
9547 data_sub = PyUnicode_DATA(substring);
9548 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9549
9550 if (direction > 0)
9551 offset = end;
9552 else
9553 offset = start;
9554
9555 if (PyUnicode_READ(kind_self, data_self, offset) ==
9556 PyUnicode_READ(kind_sub, data_sub, 0) &&
9557 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9558 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9559 /* If both are of the same kind, memcmp is sufficient */
9560 if (kind_self == kind_sub) {
9561 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009562 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009563 data_sub,
9564 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009565 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009567 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568 else {
9569 /* We do not need to compare 0 and len(substring)-1 because
9570 the if statement above ensured already that they are equal
9571 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572 for (i = 1; i < end_sub; ++i) {
9573 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9574 PyUnicode_READ(kind_sub, data_sub, i))
9575 return 0;
9576 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009577 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009578 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579 }
9580
9581 return 0;
9582}
9583
Alexander Belopolsky40018472011-02-26 01:02:56 +00009584Py_ssize_t
9585PyUnicode_Tailmatch(PyObject *str,
9586 PyObject *substr,
9587 Py_ssize_t start,
9588 Py_ssize_t end,
9589 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009590{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009591 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009592 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009593
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009594 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009595}
9596
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009597static PyObject *
9598ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009599{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009600 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9601 char *resdata, *data = PyUnicode_DATA(self);
9602 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009603
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009604 res = PyUnicode_New(len, 127);
9605 if (res == NULL)
9606 return NULL;
9607 resdata = PyUnicode_DATA(res);
9608 if (lower)
9609 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009610 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009611 _Py_bytes_upper(resdata, data, len);
9612 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613}
9614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009615static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009616handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009617{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009618 Py_ssize_t j;
9619 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009620 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009621 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009622
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009623 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9624
9625 where ! is a negation and \p{xxx} is a character with property xxx.
9626 */
9627 for (j = i - 1; j >= 0; j--) {
9628 c = PyUnicode_READ(kind, data, j);
9629 if (!_PyUnicode_IsCaseIgnorable(c))
9630 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009632 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9633 if (final_sigma) {
9634 for (j = i + 1; j < length; j++) {
9635 c = PyUnicode_READ(kind, data, j);
9636 if (!_PyUnicode_IsCaseIgnorable(c))
9637 break;
9638 }
9639 final_sigma = j == length || !_PyUnicode_IsCased(c);
9640 }
9641 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009642}
9643
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009644static int
9645lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9646 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009647{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009648 /* Obscure special case. */
9649 if (c == 0x3A3) {
9650 mapped[0] = handle_capital_sigma(kind, data, length, i);
9651 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009653 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654}
9655
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009656static Py_ssize_t
9657do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009658{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009659 Py_ssize_t i, k = 0;
9660 int n_res, j;
9661 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009662
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009663 c = PyUnicode_READ(kind, data, 0);
9664 n_res = _PyUnicode_ToUpperFull(c, mapped);
9665 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009666 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009667 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009669 for (i = 1; i < length; i++) {
9670 c = PyUnicode_READ(kind, data, i);
9671 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9672 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009673 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009674 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009675 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009676 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009677 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009678}
9679
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009680static Py_ssize_t
9681do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9682 Py_ssize_t i, k = 0;
9683
9684 for (i = 0; i < length; i++) {
9685 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9686 int n_res, j;
9687 if (Py_UNICODE_ISUPPER(c)) {
9688 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9689 }
9690 else if (Py_UNICODE_ISLOWER(c)) {
9691 n_res = _PyUnicode_ToUpperFull(c, mapped);
9692 }
9693 else {
9694 n_res = 1;
9695 mapped[0] = c;
9696 }
9697 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009698 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009699 res[k++] = mapped[j];
9700 }
9701 }
9702 return k;
9703}
9704
9705static Py_ssize_t
9706do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9707 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009708{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009709 Py_ssize_t i, k = 0;
9710
9711 for (i = 0; i < length; i++) {
9712 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9713 int n_res, j;
9714 if (lower)
9715 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9716 else
9717 n_res = _PyUnicode_ToUpperFull(c, mapped);
9718 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009719 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009720 res[k++] = mapped[j];
9721 }
9722 }
9723 return k;
9724}
9725
9726static Py_ssize_t
9727do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9728{
9729 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9730}
9731
9732static Py_ssize_t
9733do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9734{
9735 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9736}
9737
Benjamin Petersone51757f2012-01-12 21:10:29 -05009738static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009739do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9740{
9741 Py_ssize_t i, k = 0;
9742
9743 for (i = 0; i < length; i++) {
9744 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9745 Py_UCS4 mapped[3];
9746 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9747 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009748 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009749 res[k++] = mapped[j];
9750 }
9751 }
9752 return k;
9753}
9754
9755static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009756do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9757{
9758 Py_ssize_t i, k = 0;
9759 int previous_is_cased;
9760
9761 previous_is_cased = 0;
9762 for (i = 0; i < length; i++) {
9763 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9764 Py_UCS4 mapped[3];
9765 int n_res, j;
9766
9767 if (previous_is_cased)
9768 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9769 else
9770 n_res = _PyUnicode_ToTitleFull(c, mapped);
9771
9772 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009773 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009774 res[k++] = mapped[j];
9775 }
9776
9777 previous_is_cased = _PyUnicode_IsCased(c);
9778 }
9779 return k;
9780}
9781
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009782static PyObject *
9783case_operation(PyObject *self,
9784 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9785{
9786 PyObject *res = NULL;
9787 Py_ssize_t length, newlength = 0;
9788 int kind, outkind;
9789 void *data, *outdata;
9790 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9791
Benjamin Petersoneea48462012-01-16 14:28:50 -05009792 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009793
9794 kind = PyUnicode_KIND(self);
9795 data = PyUnicode_DATA(self);
9796 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009797 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009798 PyErr_SetString(PyExc_OverflowError, "string is too long");
9799 return NULL;
9800 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009801 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009802 if (tmp == NULL)
9803 return PyErr_NoMemory();
9804 newlength = perform(kind, data, length, tmp, &maxchar);
9805 res = PyUnicode_New(newlength, maxchar);
9806 if (res == NULL)
9807 goto leave;
9808 tmpend = tmp + newlength;
9809 outdata = PyUnicode_DATA(res);
9810 outkind = PyUnicode_KIND(res);
9811 switch (outkind) {
9812 case PyUnicode_1BYTE_KIND:
9813 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9814 break;
9815 case PyUnicode_2BYTE_KIND:
9816 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9817 break;
9818 case PyUnicode_4BYTE_KIND:
9819 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9820 break;
9821 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009822 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009823 }
9824 leave:
9825 PyMem_FREE(tmp);
9826 return res;
9827}
9828
Tim Peters8ce9f162004-08-27 01:49:32 +00009829PyObject *
9830PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009831{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009832 PyObject *res;
9833 PyObject *fseq;
9834 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009835 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009836
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009837 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009838 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009839 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009840 }
9841
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009842 /* NOTE: the following code can't call back into Python code,
9843 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009844 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009845
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009846 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009847 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009848 res = _PyUnicode_JoinArray(separator, items, seqlen);
9849 Py_DECREF(fseq);
9850 return res;
9851}
9852
9853PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009854_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009855{
9856 PyObject *res = NULL; /* the result */
9857 PyObject *sep = NULL;
9858 Py_ssize_t seplen;
9859 PyObject *item;
9860 Py_ssize_t sz, i, res_offset;
9861 Py_UCS4 maxchar;
9862 Py_UCS4 item_maxchar;
9863 int use_memcpy;
9864 unsigned char *res_data = NULL, *sep_data = NULL;
9865 PyObject *last_obj;
9866 unsigned int kind = 0;
9867
Tim Peters05eba1f2004-08-27 21:32:02 +00009868 /* If empty sequence, return u"". */
9869 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009870 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009871 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009872
Tim Peters05eba1f2004-08-27 21:32:02 +00009873 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009874 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009875 if (seqlen == 1) {
9876 if (PyUnicode_CheckExact(items[0])) {
9877 res = items[0];
9878 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009879 return res;
9880 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009881 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009882 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009883 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009884 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009885 /* Set up sep and seplen */
9886 if (separator == NULL) {
9887 /* fall back to a blank space separator */
9888 sep = PyUnicode_FromOrdinal(' ');
9889 if (!sep)
9890 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009891 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009892 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009893 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009894 else {
9895 if (!PyUnicode_Check(separator)) {
9896 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009897 "separator: expected str instance,"
9898 " %.80s found",
9899 Py_TYPE(separator)->tp_name);
Victor Stinneracf47b82011-10-06 12:32:37 +02009900 goto onError;
9901 }
9902 if (PyUnicode_READY(separator))
9903 goto onError;
9904 sep = separator;
9905 seplen = PyUnicode_GET_LENGTH(separator);
9906 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9907 /* inc refcount to keep this code path symmetric with the
9908 above case of a blank separator */
9909 Py_INCREF(sep);
9910 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009911 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009912 }
9913
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009914 /* There are at least two things to join, or else we have a subclass
9915 * of str in the sequence.
9916 * Do a pre-pass to figure out the total amount of space we'll
9917 * need (sz), and see whether all argument are strings.
9918 */
9919 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009920#ifdef Py_DEBUG
9921 use_memcpy = 0;
9922#else
9923 use_memcpy = 1;
9924#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009925 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009926 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009927 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009928 if (!PyUnicode_Check(item)) {
9929 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009930 "sequence item %zd: expected str instance,"
9931 " %.80s found",
9932 i, Py_TYPE(item)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009933 goto onError;
9934 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009935 if (PyUnicode_READY(item) == -1)
9936 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009937 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009938 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009939 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009940 if (i != 0) {
9941 add_sz += seplen;
9942 }
9943 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009944 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009945 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009946 goto onError;
9947 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009948 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009949 if (use_memcpy && last_obj != NULL) {
9950 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9951 use_memcpy = 0;
9952 }
9953 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009954 }
Tim Petersced69f82003-09-16 20:30:58 +00009955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009956 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009957 if (res == NULL)
9958 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009959
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009960 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009961#ifdef Py_DEBUG
9962 use_memcpy = 0;
9963#else
9964 if (use_memcpy) {
9965 res_data = PyUnicode_1BYTE_DATA(res);
9966 kind = PyUnicode_KIND(res);
9967 if (seplen != 0)
9968 sep_data = PyUnicode_1BYTE_DATA(sep);
9969 }
9970#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009971 if (use_memcpy) {
9972 for (i = 0; i < seqlen; ++i) {
9973 Py_ssize_t itemlen;
9974 item = items[i];
9975
9976 /* Copy item, and maybe the separator. */
9977 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009978 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009979 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009980 kind * seplen);
9981 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009982 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009983
9984 itemlen = PyUnicode_GET_LENGTH(item);
9985 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009986 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009987 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009988 kind * itemlen);
9989 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009990 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009991 }
9992 assert(res_data == PyUnicode_1BYTE_DATA(res)
9993 + kind * PyUnicode_GET_LENGTH(res));
9994 }
9995 else {
9996 for (i = 0, res_offset = 0; i < seqlen; ++i) {
9997 Py_ssize_t itemlen;
9998 item = items[i];
9999
10000 /* Copy item, and maybe the separator. */
10001 if (i && seplen != 0) {
10002 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10003 res_offset += seplen;
10004 }
10005
10006 itemlen = PyUnicode_GET_LENGTH(item);
10007 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010008 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010009 res_offset += itemlen;
10010 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010011 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010012 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010013 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010015 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010016 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010018
Benjamin Peterson29060642009-01-31 22:14:21 +000010019 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010021 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010022 return NULL;
10023}
10024
Victor Stinnerd3f08822012-05-29 12:57:52 +020010025void
10026_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10027 Py_UCS4 fill_char)
10028{
10029 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Victor Stinner163403a2018-11-27 12:41:17 +010010030 void *data = PyUnicode_DATA(unicode);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010031 assert(PyUnicode_IS_READY(unicode));
10032 assert(unicode_modifiable(unicode));
10033 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10034 assert(start >= 0);
10035 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner59423e32018-11-26 13:40:01 +010010036 unicode_fill(kind, data, fill_char, start, length);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010037}
10038
Victor Stinner3fe55312012-01-04 00:33:50 +010010039Py_ssize_t
10040PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10041 Py_UCS4 fill_char)
10042{
10043 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010044
10045 if (!PyUnicode_Check(unicode)) {
10046 PyErr_BadInternalCall();
10047 return -1;
10048 }
10049 if (PyUnicode_READY(unicode) == -1)
10050 return -1;
10051 if (unicode_check_modifiable(unicode))
10052 return -1;
10053
Victor Stinnerd3f08822012-05-29 12:57:52 +020010054 if (start < 0) {
10055 PyErr_SetString(PyExc_IndexError, "string index out of range");
10056 return -1;
10057 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010058 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10059 PyErr_SetString(PyExc_ValueError,
10060 "fill character is bigger than "
10061 "the string maximum character");
10062 return -1;
10063 }
10064
10065 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10066 length = Py_MIN(maxlen, length);
10067 if (length <= 0)
10068 return 0;
10069
Victor Stinnerd3f08822012-05-29 12:57:52 +020010070 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010071 return length;
10072}
10073
Victor Stinner9310abb2011-10-05 00:59:23 +020010074static PyObject *
10075pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010076 Py_ssize_t left,
10077 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010078 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010079{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 PyObject *u;
10081 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010082 int kind;
10083 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010084
10085 if (left < 0)
10086 left = 0;
10087 if (right < 0)
10088 right = 0;
10089
Victor Stinnerc4b49542011-12-11 22:44:26 +010010090 if (left == 0 && right == 0)
10091 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010092
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10094 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010095 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10096 return NULL;
10097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010099 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010101 if (!u)
10102 return NULL;
10103
10104 kind = PyUnicode_KIND(u);
10105 data = PyUnicode_DATA(u);
10106 if (left)
Victor Stinner59423e32018-11-26 13:40:01 +010010107 unicode_fill(kind, data, fill, 0, left);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010108 if (right)
Victor Stinner59423e32018-11-26 13:40:01 +010010109 unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010110 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010111 assert(_PyUnicode_CheckConsistency(u, 1));
10112 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010113}
10114
Alexander Belopolsky40018472011-02-26 01:02:56 +000010115PyObject *
10116PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010117{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010118 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010119
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010120 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010121 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010122
Benjamin Petersonead6b532011-12-20 17:23:42 -060010123 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010125 if (PyUnicode_IS_ASCII(string))
10126 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010127 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010128 PyUnicode_GET_LENGTH(string), keepends);
10129 else
10130 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010131 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010132 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133 break;
10134 case PyUnicode_2BYTE_KIND:
10135 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010136 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 PyUnicode_GET_LENGTH(string), keepends);
10138 break;
10139 case PyUnicode_4BYTE_KIND:
10140 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010141 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 PyUnicode_GET_LENGTH(string), keepends);
10143 break;
10144 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010145 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010147 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010148}
10149
Alexander Belopolsky40018472011-02-26 01:02:56 +000010150static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010151split(PyObject *self,
10152 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010153 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010154{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010155 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 void *buf1, *buf2;
10157 Py_ssize_t len1, len2;
10158 PyObject* out;
10159
Guido van Rossumd57fd912000-03-10 22:53:23 +000010160 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010161 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 if (PyUnicode_READY(self) == -1)
10164 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010166 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010167 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010169 if (PyUnicode_IS_ASCII(self))
10170 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010171 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010172 PyUnicode_GET_LENGTH(self), maxcount
10173 );
10174 else
10175 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010176 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010177 PyUnicode_GET_LENGTH(self), maxcount
10178 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 case PyUnicode_2BYTE_KIND:
10180 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010181 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 PyUnicode_GET_LENGTH(self), maxcount
10183 );
10184 case PyUnicode_4BYTE_KIND:
10185 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010186 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010187 PyUnicode_GET_LENGTH(self), maxcount
10188 );
10189 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010190 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 }
10192
10193 if (PyUnicode_READY(substring) == -1)
10194 return NULL;
10195
10196 kind1 = PyUnicode_KIND(self);
10197 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 len1 = PyUnicode_GET_LENGTH(self);
10199 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010200 if (kind1 < kind2 || len1 < len2) {
10201 out = PyList_New(1);
10202 if (out == NULL)
10203 return NULL;
10204 Py_INCREF(self);
10205 PyList_SET_ITEM(out, 0, self);
10206 return out;
10207 }
10208 buf1 = PyUnicode_DATA(self);
10209 buf2 = PyUnicode_DATA(substring);
10210 if (kind2 != kind1) {
10211 buf2 = _PyUnicode_AsKind(substring, kind1);
10212 if (!buf2)
10213 return NULL;
10214 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010216 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010218 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10219 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010220 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010221 else
10222 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010223 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 break;
10225 case PyUnicode_2BYTE_KIND:
10226 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010227 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 break;
10229 case PyUnicode_4BYTE_KIND:
10230 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010231 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 break;
10233 default:
10234 out = NULL;
10235 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010236 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 PyMem_Free(buf2);
10238 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010239}
10240
Alexander Belopolsky40018472011-02-26 01:02:56 +000010241static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010242rsplit(PyObject *self,
10243 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010244 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010245{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010246 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 void *buf1, *buf2;
10248 Py_ssize_t len1, len2;
10249 PyObject* out;
10250
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010251 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010252 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 if (PyUnicode_READY(self) == -1)
10255 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010258 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010260 if (PyUnicode_IS_ASCII(self))
10261 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010262 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010263 PyUnicode_GET_LENGTH(self), maxcount
10264 );
10265 else
10266 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010267 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010268 PyUnicode_GET_LENGTH(self), maxcount
10269 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 case PyUnicode_2BYTE_KIND:
10271 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010272 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 PyUnicode_GET_LENGTH(self), maxcount
10274 );
10275 case PyUnicode_4BYTE_KIND:
10276 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010277 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 PyUnicode_GET_LENGTH(self), maxcount
10279 );
10280 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010281 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 }
10283
10284 if (PyUnicode_READY(substring) == -1)
10285 return NULL;
10286
10287 kind1 = PyUnicode_KIND(self);
10288 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 len1 = PyUnicode_GET_LENGTH(self);
10290 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010291 if (kind1 < kind2 || len1 < len2) {
10292 out = PyList_New(1);
10293 if (out == NULL)
10294 return NULL;
10295 Py_INCREF(self);
10296 PyList_SET_ITEM(out, 0, self);
10297 return out;
10298 }
10299 buf1 = PyUnicode_DATA(self);
10300 buf2 = PyUnicode_DATA(substring);
10301 if (kind2 != kind1) {
10302 buf2 = _PyUnicode_AsKind(substring, kind1);
10303 if (!buf2)
10304 return NULL;
10305 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010307 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010309 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10310 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010311 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010312 else
10313 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010314 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 break;
10316 case PyUnicode_2BYTE_KIND:
10317 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010318 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 break;
10320 case PyUnicode_4BYTE_KIND:
10321 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010322 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 break;
10324 default:
10325 out = NULL;
10326 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010327 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 PyMem_Free(buf2);
10329 return out;
10330}
10331
10332static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010333anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10334 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010335{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010336 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010338 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10339 return asciilib_find(buf1, len1, buf2, len2, offset);
10340 else
10341 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 case PyUnicode_2BYTE_KIND:
10343 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10344 case PyUnicode_4BYTE_KIND:
10345 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10346 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010347 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348}
10349
10350static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010351anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10352 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010354 switch (kind) {
10355 case PyUnicode_1BYTE_KIND:
10356 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10357 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10358 else
10359 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10360 case PyUnicode_2BYTE_KIND:
10361 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10362 case PyUnicode_4BYTE_KIND:
10363 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10364 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010365 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010366}
10367
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010368static void
10369replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10370 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10371{
10372 int kind = PyUnicode_KIND(u);
10373 void *data = PyUnicode_DATA(u);
10374 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10375 if (kind == PyUnicode_1BYTE_KIND) {
10376 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10377 (Py_UCS1 *)data + len,
10378 u1, u2, maxcount);
10379 }
10380 else if (kind == PyUnicode_2BYTE_KIND) {
10381 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10382 (Py_UCS2 *)data + len,
10383 u1, u2, maxcount);
10384 }
10385 else {
10386 assert(kind == PyUnicode_4BYTE_KIND);
10387 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10388 (Py_UCS4 *)data + len,
10389 u1, u2, maxcount);
10390 }
10391}
10392
Alexander Belopolsky40018472011-02-26 01:02:56 +000010393static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010394replace(PyObject *self, PyObject *str1,
10395 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010396{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 PyObject *u;
10398 char *sbuf = PyUnicode_DATA(self);
10399 char *buf1 = PyUnicode_DATA(str1);
10400 char *buf2 = PyUnicode_DATA(str2);
10401 int srelease = 0, release1 = 0, release2 = 0;
10402 int skind = PyUnicode_KIND(self);
10403 int kind1 = PyUnicode_KIND(str1);
10404 int kind2 = PyUnicode_KIND(str2);
10405 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10406 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10407 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010408 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010409 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010410
10411 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010412 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010414 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010415
Victor Stinner59de0ee2011-10-07 10:01:28 +020010416 if (str1 == str2)
10417 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418
Victor Stinner49a0a212011-10-12 23:46:10 +020010419 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010420 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10421 if (maxchar < maxchar_str1)
10422 /* substring too wide to be present */
10423 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010424 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10425 /* Replacing str1 with str2 may cause a maxchar reduction in the
10426 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010427 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010428 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010430 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010431 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010433 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010435 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010436 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010437 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010438
Victor Stinner69ed0f42013-04-09 21:48:24 +020010439 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010440 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010441 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010442 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010443 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010445 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010447
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010448 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10449 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010450 }
10451 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 int rkind = skind;
10453 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010454 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010456 if (kind1 < rkind) {
10457 /* widen substring */
10458 buf1 = _PyUnicode_AsKind(str1, rkind);
10459 if (!buf1) goto error;
10460 release1 = 1;
10461 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010462 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010463 if (i < 0)
10464 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 if (rkind > kind2) {
10466 /* widen replacement */
10467 buf2 = _PyUnicode_AsKind(str2, rkind);
10468 if (!buf2) goto error;
10469 release2 = 1;
10470 }
10471 else if (rkind < kind2) {
10472 /* widen self and buf1 */
10473 rkind = kind2;
10474 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010475 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 sbuf = _PyUnicode_AsKind(self, rkind);
10477 if (!sbuf) goto error;
10478 srelease = 1;
10479 buf1 = _PyUnicode_AsKind(str1, rkind);
10480 if (!buf1) goto error;
10481 release1 = 1;
10482 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010483 u = PyUnicode_New(slen, maxchar);
10484 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010486 assert(PyUnicode_KIND(u) == rkind);
10487 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010488
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010489 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010490 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010491 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010492 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010493 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010494 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010495
10496 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010497 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010498 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010499 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010500 if (i == -1)
10501 break;
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 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010508 }
10509 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010510 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010511 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010512 int rkind = skind;
10513 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010516 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 buf1 = _PyUnicode_AsKind(str1, rkind);
10518 if (!buf1) goto error;
10519 release1 = 1;
10520 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010521 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010522 if (n == 0)
10523 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010525 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010526 buf2 = _PyUnicode_AsKind(str2, rkind);
10527 if (!buf2) goto error;
10528 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010531 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010532 rkind = kind2;
10533 sbuf = _PyUnicode_AsKind(self, rkind);
10534 if (!sbuf) goto error;
10535 srelease = 1;
10536 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010537 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010538 buf1 = _PyUnicode_AsKind(str1, rkind);
10539 if (!buf1) goto error;
10540 release1 = 1;
10541 }
10542 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10543 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010544 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010545 PyErr_SetString(PyExc_OverflowError,
10546 "replace string is too long");
10547 goto error;
10548 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010549 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010550 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010551 _Py_INCREF_UNICODE_EMPTY();
10552 if (!unicode_empty)
10553 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010554 u = unicode_empty;
10555 goto done;
10556 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010557 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010558 PyErr_SetString(PyExc_OverflowError,
10559 "replace string is too long");
10560 goto error;
10561 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010562 u = PyUnicode_New(new_size, maxchar);
10563 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010565 assert(PyUnicode_KIND(u) == rkind);
10566 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 ires = i = 0;
10568 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010569 while (n-- > 0) {
10570 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010571 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010572 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010573 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010574 if (j == -1)
10575 break;
10576 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010577 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010578 memcpy(res + rkind * ires,
10579 sbuf + rkind * i,
10580 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010582 }
10583 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010585 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010586 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010587 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010589 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010590 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010591 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010593 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010594 memcpy(res + rkind * ires,
10595 sbuf + rkind * i,
10596 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010597 }
10598 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010599 /* interleave */
10600 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010601 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010603 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010605 if (--n <= 0)
10606 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010607 memcpy(res + rkind * ires,
10608 sbuf + rkind * i,
10609 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 ires++;
10611 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010612 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010613 memcpy(res + rkind * ires,
10614 sbuf + rkind * i,
10615 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010616 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010617 }
10618
10619 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010620 unicode_adjust_maxchar(&u);
10621 if (u == NULL)
10622 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010623 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010624
10625 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010626 if (srelease)
10627 PyMem_FREE(sbuf);
10628 if (release1)
10629 PyMem_FREE(buf1);
10630 if (release2)
10631 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010632 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010634
Benjamin Peterson29060642009-01-31 22:14:21 +000010635 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010636 /* nothing to replace; return original string (when possible) */
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 Stinnerc4b49542011-12-11 22:44:26 +010010643 return unicode_result_unchanged(self);
10644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010645 error:
10646 if (srelease && sbuf)
10647 PyMem_FREE(sbuf);
10648 if (release1 && buf1)
10649 PyMem_FREE(buf1);
10650 if (release2 && buf2)
10651 PyMem_FREE(buf2);
10652 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010653}
10654
10655/* --- Unicode Object Methods --------------------------------------------- */
10656
INADA Naoki3ae20562017-01-16 20:41:20 +090010657/*[clinic input]
10658str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010659
INADA Naoki3ae20562017-01-16 20:41:20 +090010660Return a version of the string where each word is titlecased.
10661
10662More specifically, words start with uppercased characters and all remaining
10663cased characters have lower case.
10664[clinic start generated code]*/
10665
10666static PyObject *
10667unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010668/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010669{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010670 if (PyUnicode_READY(self) == -1)
10671 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010672 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010673}
10674
INADA Naoki3ae20562017-01-16 20:41:20 +090010675/*[clinic input]
10676str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677
INADA Naoki3ae20562017-01-16 20:41:20 +090010678Return a capitalized version of the string.
10679
10680More specifically, make the first character have upper case and the rest lower
10681case.
10682[clinic start generated code]*/
10683
10684static PyObject *
10685unicode_capitalize_impl(PyObject *self)
10686/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010687{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010688 if (PyUnicode_READY(self) == -1)
10689 return NULL;
10690 if (PyUnicode_GET_LENGTH(self) == 0)
10691 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010692 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010693}
10694
INADA Naoki3ae20562017-01-16 20:41:20 +090010695/*[clinic input]
10696str.casefold as unicode_casefold
10697
10698Return a version of the string suitable for caseless comparisons.
10699[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010700
10701static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010702unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010703/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010704{
10705 if (PyUnicode_READY(self) == -1)
10706 return NULL;
10707 if (PyUnicode_IS_ASCII(self))
10708 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010709 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010710}
10711
10712
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010713/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010714
10715static int
10716convert_uc(PyObject *obj, void *addr)
10717{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010718 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010719
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010720 if (!PyUnicode_Check(obj)) {
10721 PyErr_Format(PyExc_TypeError,
10722 "The fill character must be a unicode character, "
Victor Stinner998b8062018-09-12 00:23:25 +020010723 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010724 return 0;
10725 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010726 if (PyUnicode_READY(obj) < 0)
10727 return 0;
10728 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010729 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010730 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010731 return 0;
10732 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010733 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010734 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010735}
10736
INADA Naoki3ae20562017-01-16 20:41:20 +090010737/*[clinic input]
10738str.center as unicode_center
10739
10740 width: Py_ssize_t
10741 fillchar: Py_UCS4 = ' '
10742 /
10743
10744Return a centered string of length width.
10745
10746Padding is done using the specified fill character (default is a space).
10747[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010748
10749static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010750unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10751/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010752{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010753 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010754
Benjamin Petersonbac79492012-01-14 13:34:47 -050010755 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756 return NULL;
10757
Victor Stinnerc4b49542011-12-11 22:44:26 +010010758 if (PyUnicode_GET_LENGTH(self) >= width)
10759 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760
Victor Stinnerc4b49542011-12-11 22:44:26 +010010761 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762 left = marg / 2 + (marg & width & 1);
10763
Victor Stinner9310abb2011-10-05 00:59:23 +020010764 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010765}
10766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010767/* This function assumes that str1 and str2 are readied by the caller. */
10768
Marc-André Lemburge5034372000-08-08 08:04:29 +000010769static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010770unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010771{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010772#define COMPARE(TYPE1, TYPE2) \
10773 do { \
10774 TYPE1* p1 = (TYPE1 *)data1; \
10775 TYPE2* p2 = (TYPE2 *)data2; \
10776 TYPE1* end = p1 + len; \
10777 Py_UCS4 c1, c2; \
10778 for (; p1 != end; p1++, p2++) { \
10779 c1 = *p1; \
10780 c2 = *p2; \
10781 if (c1 != c2) \
10782 return (c1 < c2) ? -1 : 1; \
10783 } \
10784 } \
10785 while (0)
10786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 int kind1, kind2;
10788 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010789 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010791 kind1 = PyUnicode_KIND(str1);
10792 kind2 = PyUnicode_KIND(str2);
10793 data1 = PyUnicode_DATA(str1);
10794 data2 = PyUnicode_DATA(str2);
10795 len1 = PyUnicode_GET_LENGTH(str1);
10796 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010797 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010798
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010799 switch(kind1) {
10800 case PyUnicode_1BYTE_KIND:
10801 {
10802 switch(kind2) {
10803 case PyUnicode_1BYTE_KIND:
10804 {
10805 int cmp = memcmp(data1, data2, len);
10806 /* normalize result of memcmp() into the range [-1; 1] */
10807 if (cmp < 0)
10808 return -1;
10809 if (cmp > 0)
10810 return 1;
10811 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010812 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010813 case PyUnicode_2BYTE_KIND:
10814 COMPARE(Py_UCS1, Py_UCS2);
10815 break;
10816 case PyUnicode_4BYTE_KIND:
10817 COMPARE(Py_UCS1, Py_UCS4);
10818 break;
10819 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010820 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010821 }
10822 break;
10823 }
10824 case PyUnicode_2BYTE_KIND:
10825 {
10826 switch(kind2) {
10827 case PyUnicode_1BYTE_KIND:
10828 COMPARE(Py_UCS2, Py_UCS1);
10829 break;
10830 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010831 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010832 COMPARE(Py_UCS2, Py_UCS2);
10833 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010834 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010835 case PyUnicode_4BYTE_KIND:
10836 COMPARE(Py_UCS2, Py_UCS4);
10837 break;
10838 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010839 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010840 }
10841 break;
10842 }
10843 case PyUnicode_4BYTE_KIND:
10844 {
10845 switch(kind2) {
10846 case PyUnicode_1BYTE_KIND:
10847 COMPARE(Py_UCS4, Py_UCS1);
10848 break;
10849 case PyUnicode_2BYTE_KIND:
10850 COMPARE(Py_UCS4, Py_UCS2);
10851 break;
10852 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010853 {
10854#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10855 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10856 /* normalize result of wmemcmp() into the range [-1; 1] */
10857 if (cmp < 0)
10858 return -1;
10859 if (cmp > 0)
10860 return 1;
10861#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010862 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010863#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010864 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010865 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010866 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010867 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010868 }
10869 break;
10870 }
10871 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010872 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010873 }
10874
Victor Stinner770e19e2012-10-04 22:59:45 +020010875 if (len1 == len2)
10876 return 0;
10877 if (len1 < len2)
10878 return -1;
10879 else
10880 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010881
10882#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010883}
10884
Benjamin Peterson621b4302016-09-09 13:54:34 -070010885static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010886unicode_compare_eq(PyObject *str1, PyObject *str2)
10887{
10888 int kind;
10889 void *data1, *data2;
10890 Py_ssize_t len;
10891 int cmp;
10892
Victor Stinnere5567ad2012-10-23 02:48:49 +020010893 len = PyUnicode_GET_LENGTH(str1);
10894 if (PyUnicode_GET_LENGTH(str2) != len)
10895 return 0;
10896 kind = PyUnicode_KIND(str1);
10897 if (PyUnicode_KIND(str2) != kind)
10898 return 0;
10899 data1 = PyUnicode_DATA(str1);
10900 data2 = PyUnicode_DATA(str2);
10901
10902 cmp = memcmp(data1, data2, len * kind);
10903 return (cmp == 0);
10904}
10905
10906
Alexander Belopolsky40018472011-02-26 01:02:56 +000010907int
10908PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010910 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10911 if (PyUnicode_READY(left) == -1 ||
10912 PyUnicode_READY(right) == -1)
10913 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010914
10915 /* a string is equal to itself */
10916 if (left == right)
10917 return 0;
10918
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010919 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010920 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010921 PyErr_Format(PyExc_TypeError,
10922 "Can't compare %.100s and %.100s",
10923 left->ob_type->tp_name,
10924 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925 return -1;
10926}
10927
Martin v. Löwis5b222132007-06-10 09:51:05 +000010928int
10929PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10930{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 Py_ssize_t i;
10932 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010933 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010934 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010935
Victor Stinner910337b2011-10-03 03:20:16 +020010936 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010937 if (!PyUnicode_IS_READY(uni)) {
10938 const wchar_t *ws = _PyUnicode_WSTR(uni);
10939 /* Compare Unicode string and source character set string */
10940 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10941 if (chr != ustr[i])
10942 return (chr < ustr[i]) ? -1 : 1;
10943 }
10944 /* This check keeps Python strings that end in '\0' from comparing equal
10945 to C strings identical up to that point. */
10946 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10947 return 1; /* uni is longer */
10948 if (ustr[i])
10949 return -1; /* str is longer */
10950 return 0;
10951 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010953 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010954 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010955 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010956 size_t len, len2 = strlen(str);
10957 int cmp;
10958
10959 len = Py_MIN(len1, len2);
10960 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010961 if (cmp != 0) {
10962 if (cmp < 0)
10963 return -1;
10964 else
10965 return 1;
10966 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010967 if (len1 > len2)
10968 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010969 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010970 return -1; /* str is longer */
10971 return 0;
10972 }
10973 else {
10974 void *data = PyUnicode_DATA(uni);
10975 /* Compare Unicode string and source character set string */
10976 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010977 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010978 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10979 /* This check keeps Python strings that end in '\0' from comparing equal
10980 to C strings identical up to that point. */
10981 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10982 return 1; /* uni is longer */
10983 if (str[i])
10984 return -1; /* str is longer */
10985 return 0;
10986 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000010987}
10988
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020010989static int
10990non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
10991{
10992 size_t i, len;
10993 const wchar_t *p;
10994 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
10995 if (strlen(str) != len)
10996 return 0;
10997 p = _PyUnicode_WSTR(unicode);
10998 assert(p);
10999 for (i = 0; i < len; i++) {
11000 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011001 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011002 return 0;
11003 }
11004 return 1;
11005}
11006
11007int
11008_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11009{
11010 size_t len;
11011 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011012 assert(str);
11013#ifndef NDEBUG
11014 for (const char *p = str; *p; p++) {
11015 assert((unsigned char)*p < 128);
11016 }
11017#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011018 if (PyUnicode_READY(unicode) == -1) {
11019 /* Memory error or bad data */
11020 PyErr_Clear();
11021 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11022 }
11023 if (!PyUnicode_IS_ASCII(unicode))
11024 return 0;
11025 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11026 return strlen(str) == len &&
11027 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11028}
11029
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011030int
11031_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11032{
11033 PyObject *right_uni;
11034 Py_hash_t hash;
11035
11036 assert(_PyUnicode_CHECK(left));
11037 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011038#ifndef NDEBUG
11039 for (const char *p = right->string; *p; p++) {
11040 assert((unsigned char)*p < 128);
11041 }
11042#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011043
11044 if (PyUnicode_READY(left) == -1) {
11045 /* memory error or bad data */
11046 PyErr_Clear();
11047 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11048 }
11049
11050 if (!PyUnicode_IS_ASCII(left))
11051 return 0;
11052
11053 right_uni = _PyUnicode_FromId(right); /* borrowed */
11054 if (right_uni == NULL) {
11055 /* memory error or bad data */
11056 PyErr_Clear();
11057 return _PyUnicode_EqualToASCIIString(left, right->string);
11058 }
11059
11060 if (left == right_uni)
11061 return 1;
11062
11063 if (PyUnicode_CHECK_INTERNED(left))
11064 return 0;
11065
INADA Naoki7cc95f52018-01-28 02:07:09 +090011066 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011067 hash = _PyUnicode_HASH(left);
11068 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11069 return 0;
11070
11071 return unicode_compare_eq(left, right_uni);
11072}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011073
Alexander Belopolsky40018472011-02-26 01:02:56 +000011074PyObject *
11075PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011076{
11077 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011078
Victor Stinnere5567ad2012-10-23 02:48:49 +020011079 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11080 Py_RETURN_NOTIMPLEMENTED;
11081
11082 if (PyUnicode_READY(left) == -1 ||
11083 PyUnicode_READY(right) == -1)
11084 return NULL;
11085
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011086 if (left == right) {
11087 switch (op) {
11088 case Py_EQ:
11089 case Py_LE:
11090 case Py_GE:
11091 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011092 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011093 case Py_NE:
11094 case Py_LT:
11095 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011096 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011097 default:
11098 PyErr_BadArgument();
11099 return NULL;
11100 }
11101 }
11102 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011103 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011104 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011105 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011106 }
11107 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011108 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011109 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011110 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011111}
11112
Alexander Belopolsky40018472011-02-26 01:02:56 +000011113int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011114_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11115{
11116 return unicode_eq(aa, bb);
11117}
11118
11119int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011120PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011121{
Victor Stinner77282cb2013-04-14 19:22:47 +020011122 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011123 void *buf1, *buf2;
11124 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011125 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011126
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011127 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011128 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020011129 "'in <string>' requires string as left operand, not %.100s",
11130 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011131 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011132 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011133 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011134 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011135 if (ensure_unicode(str) < 0)
11136 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011139 kind2 = PyUnicode_KIND(substr);
11140 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011141 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011142 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011143 len2 = PyUnicode_GET_LENGTH(substr);
11144 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011145 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011146 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011147 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011148 if (len2 == 1) {
11149 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11150 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011151 return result;
11152 }
11153 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011154 buf2 = _PyUnicode_AsKind(substr, kind1);
11155 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011156 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011157 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158
Victor Stinner77282cb2013-04-14 19:22:47 +020011159 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 case PyUnicode_1BYTE_KIND:
11161 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11162 break;
11163 case PyUnicode_2BYTE_KIND:
11164 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11165 break;
11166 case PyUnicode_4BYTE_KIND:
11167 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11168 break;
11169 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011170 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011171 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011172
Victor Stinner77282cb2013-04-14 19:22:47 +020011173 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011174 PyMem_Free(buf2);
11175
Guido van Rossum403d68b2000-03-13 15:55:09 +000011176 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011177}
11178
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179/* Concat to string or Unicode object giving a new Unicode object. */
11180
Alexander Belopolsky40018472011-02-26 01:02:56 +000011181PyObject *
11182PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011184 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011185 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011186 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011188 if (ensure_unicode(left) < 0)
11189 return NULL;
11190
11191 if (!PyUnicode_Check(right)) {
11192 PyErr_Format(PyExc_TypeError,
11193 "can only concatenate str (not \"%.200s\") to str",
11194 right->ob_type->tp_name);
11195 return NULL;
11196 }
11197 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011198 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199
11200 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011201 if (left == unicode_empty)
11202 return PyUnicode_FromObject(right);
11203 if (right == unicode_empty)
11204 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011205
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011206 left_len = PyUnicode_GET_LENGTH(left);
11207 right_len = PyUnicode_GET_LENGTH(right);
11208 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011209 PyErr_SetString(PyExc_OverflowError,
11210 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011211 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011212 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011213 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011214
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011215 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11216 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011217 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011218
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011220 result = PyUnicode_New(new_len, maxchar);
11221 if (result == NULL)
11222 return NULL;
11223 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11224 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11225 assert(_PyUnicode_CheckConsistency(result, 1));
11226 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227}
11228
Walter Dörwald1ab83302007-05-18 17:15:44 +000011229void
Victor Stinner23e56682011-10-03 03:54:37 +020011230PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011231{
Victor Stinner23e56682011-10-03 03:54:37 +020011232 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011233 Py_UCS4 maxchar, maxchar2;
11234 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011235
11236 if (p_left == NULL) {
11237 if (!PyErr_Occurred())
11238 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011239 return;
11240 }
Victor Stinner23e56682011-10-03 03:54:37 +020011241 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011242 if (right == NULL || left == NULL
11243 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011244 if (!PyErr_Occurred())
11245 PyErr_BadInternalCall();
11246 goto error;
11247 }
11248
Benjamin Petersonbac79492012-01-14 13:34:47 -050011249 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011250 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011251 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011252 goto error;
11253
Victor Stinner488fa492011-12-12 00:01:39 +010011254 /* Shortcuts */
11255 if (left == unicode_empty) {
11256 Py_DECREF(left);
11257 Py_INCREF(right);
11258 *p_left = right;
11259 return;
11260 }
11261 if (right == unicode_empty)
11262 return;
11263
11264 left_len = PyUnicode_GET_LENGTH(left);
11265 right_len = PyUnicode_GET_LENGTH(right);
11266 if (left_len > PY_SSIZE_T_MAX - right_len) {
11267 PyErr_SetString(PyExc_OverflowError,
11268 "strings are too large to concat");
11269 goto error;
11270 }
11271 new_len = left_len + right_len;
11272
11273 if (unicode_modifiable(left)
11274 && PyUnicode_CheckExact(right)
11275 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011276 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11277 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011278 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011279 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011280 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11281 {
11282 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011283 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011284 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011285
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011286 /* copy 'right' into the newly allocated area of 'left' */
11287 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011288 }
Victor Stinner488fa492011-12-12 00:01:39 +010011289 else {
11290 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11291 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011292 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011293
Victor Stinner488fa492011-12-12 00:01:39 +010011294 /* Concat the two Unicode strings */
11295 res = PyUnicode_New(new_len, maxchar);
11296 if (res == NULL)
11297 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011298 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11299 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011300 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011301 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011302 }
11303 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011304 return;
11305
11306error:
Victor Stinner488fa492011-12-12 00:01:39 +010011307 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011308}
11309
11310void
11311PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11312{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011313 PyUnicode_Append(pleft, right);
11314 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011315}
11316
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011317/*
11318Wraps stringlib_parse_args_finds() and additionally ensures that the
11319first argument is a unicode object.
11320*/
11321
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011322static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011323parse_args_finds_unicode(const char * function_name, PyObject *args,
11324 PyObject **substring,
11325 Py_ssize_t *start, Py_ssize_t *end)
11326{
11327 if(stringlib_parse_args_finds(function_name, args, substring,
11328 start, end)) {
11329 if (ensure_unicode(*substring) < 0)
11330 return 0;
11331 return 1;
11332 }
11333 return 0;
11334}
11335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011336PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011337 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011339Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011340string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011341interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342
11343static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011344unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011346 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011347 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011348 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011350 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 void *buf1, *buf2;
11352 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011354 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011355 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 kind1 = PyUnicode_KIND(self);
11358 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011359 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011360 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011361
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011362 len1 = PyUnicode_GET_LENGTH(self);
11363 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011365 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011366 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011367
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011368 buf1 = PyUnicode_DATA(self);
11369 buf2 = PyUnicode_DATA(substring);
11370 if (kind2 != kind1) {
11371 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011372 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011373 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011374 }
11375 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 case PyUnicode_1BYTE_KIND:
11377 iresult = ucs1lib_count(
11378 ((Py_UCS1*)buf1) + start, end - start,
11379 buf2, len2, PY_SSIZE_T_MAX
11380 );
11381 break;
11382 case PyUnicode_2BYTE_KIND:
11383 iresult = ucs2lib_count(
11384 ((Py_UCS2*)buf1) + start, end - start,
11385 buf2, len2, PY_SSIZE_T_MAX
11386 );
11387 break;
11388 case PyUnicode_4BYTE_KIND:
11389 iresult = ucs4lib_count(
11390 ((Py_UCS4*)buf1) + start, end - start,
11391 buf2, len2, PY_SSIZE_T_MAX
11392 );
11393 break;
11394 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011395 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396 }
11397
11398 result = PyLong_FromSsize_t(iresult);
11399
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011400 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402
Guido van Rossumd57fd912000-03-10 22:53:23 +000011403 return result;
11404}
11405
INADA Naoki3ae20562017-01-16 20:41:20 +090011406/*[clinic input]
11407str.encode as unicode_encode
11408
11409 encoding: str(c_default="NULL") = 'utf-8'
11410 The encoding in which to encode the string.
11411 errors: str(c_default="NULL") = 'strict'
11412 The error handling scheme to use for encoding errors.
11413 The default is 'strict' meaning that encoding errors raise a
11414 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11415 'xmlcharrefreplace' as well as any other name registered with
11416 codecs.register_error that can handle UnicodeEncodeErrors.
11417
11418Encode the string using the codec registered for encoding.
11419[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
11421static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011422unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011423/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011425 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011426}
11427
INADA Naoki3ae20562017-01-16 20:41:20 +090011428/*[clinic input]
11429str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430
INADA Naoki3ae20562017-01-16 20:41:20 +090011431 tabsize: int = 8
11432
11433Return a copy where all tab characters are expanded using spaces.
11434
11435If tabsize is not given, a tab size of 8 characters is assumed.
11436[clinic start generated code]*/
11437
11438static PyObject *
11439unicode_expandtabs_impl(PyObject *self, int tabsize)
11440/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011442 Py_ssize_t i, j, line_pos, src_len, incr;
11443 Py_UCS4 ch;
11444 PyObject *u;
11445 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011446 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011447 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448
Antoine Pitrou22425222011-10-04 19:10:51 +020011449 if (PyUnicode_READY(self) == -1)
11450 return NULL;
11451
Thomas Wouters7e474022000-07-16 12:04:32 +000011452 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011453 src_len = PyUnicode_GET_LENGTH(self);
11454 i = j = line_pos = 0;
11455 kind = PyUnicode_KIND(self);
11456 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011457 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011458 for (; i < src_len; i++) {
11459 ch = PyUnicode_READ(kind, src_data, i);
11460 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011461 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011463 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011464 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011465 goto overflow;
11466 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011467 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011468 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011472 goto overflow;
11473 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011474 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011475 if (ch == '\n' || ch == '\r')
11476 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011478 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011479 if (!found)
11480 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011481
Guido van Rossumd57fd912000-03-10 22:53:23 +000011482 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011483 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 if (!u)
11485 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487
Antoine Pitroue71d5742011-10-04 15:55:09 +020011488 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489
Antoine Pitroue71d5742011-10-04 15:55:09 +020011490 for (; i < src_len; i++) {
11491 ch = PyUnicode_READ(kind, src_data, i);
11492 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011493 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011494 incr = tabsize - (line_pos % tabsize);
11495 line_pos += incr;
Victor Stinner59423e32018-11-26 13:40:01 +010011496 unicode_fill(kind, dest_data, ' ', j, incr);
Victor Stinnerda79e632012-02-22 13:37:04 +010011497 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011498 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011499 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011500 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011501 line_pos++;
11502 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011503 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011504 if (ch == '\n' || ch == '\r')
11505 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011507 }
11508 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011509 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011510
Antoine Pitroue71d5742011-10-04 15:55:09 +020011511 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011512 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11513 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514}
11515
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011516PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518\n\
11519Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011520such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521arguments start and end are interpreted as in slice notation.\n\
11522\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011523Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524
11525static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011528 /* initialize variables to prevent gcc warning */
11529 PyObject *substring = NULL;
11530 Py_ssize_t start = 0;
11531 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011532 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011534 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011537 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011538 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011539
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011540 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 if (result == -2)
11543 return NULL;
11544
Christian Heimes217cfd12007-12-02 14:31:20 +000011545 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546}
11547
11548static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011549unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011551 void *data;
11552 enum PyUnicode_Kind kind;
11553 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011554
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011555 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011556 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011558 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011559 if (PyUnicode_READY(self) == -1) {
11560 return NULL;
11561 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011562 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11563 PyErr_SetString(PyExc_IndexError, "string index out of range");
11564 return NULL;
11565 }
11566 kind = PyUnicode_KIND(self);
11567 data = PyUnicode_DATA(self);
11568 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011569 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570}
11571
Guido van Rossumc2504932007-09-18 19:42:40 +000011572/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011573 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011574static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011575unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576{
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011577 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011578
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011579#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011580 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011581#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011582 if (_PyUnicode_HASH(self) != -1)
11583 return _PyUnicode_HASH(self);
11584 if (PyUnicode_READY(self) == -1)
11585 return -1;
animalizea1d14252019-01-02 20:16:06 +080011586
Christian Heimes985ecdc2013-11-20 11:46:18 +010011587 x = _Py_HashBytes(PyUnicode_DATA(self),
11588 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011590 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591}
11592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011593PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011594 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595\n\
oldkaa0735f2018-02-02 16:52:55 +080011596Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011597such that sub is contained within S[start:end]. Optional\n\
11598arguments start and end are interpreted as in slice notation.\n\
11599\n\
11600Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601
11602static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011605 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011606 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011607 PyObject *substring = NULL;
11608 Py_ssize_t start = 0;
11609 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011611 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011614 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011617 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011618
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 if (result == -2)
11620 return NULL;
11621
Guido van Rossumd57fd912000-03-10 22:53:23 +000011622 if (result < 0) {
11623 PyErr_SetString(PyExc_ValueError, "substring not found");
11624 return NULL;
11625 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011626
Christian Heimes217cfd12007-12-02 14:31:20 +000011627 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628}
11629
INADA Naoki3ae20562017-01-16 20:41:20 +090011630/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011631str.isascii as unicode_isascii
11632
11633Return True if all characters in the string are ASCII, False otherwise.
11634
11635ASCII characters have code points in the range U+0000-U+007F.
11636Empty string is ASCII too.
11637[clinic start generated code]*/
11638
11639static PyObject *
11640unicode_isascii_impl(PyObject *self)
11641/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11642{
11643 if (PyUnicode_READY(self) == -1) {
11644 return NULL;
11645 }
11646 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11647}
11648
11649/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011650str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651
INADA Naoki3ae20562017-01-16 20:41:20 +090011652Return True if the string is a lowercase string, False otherwise.
11653
11654A string is lowercase if all cased characters in the string are lowercase and
11655there is at least one cased character in the string.
11656[clinic start generated code]*/
11657
11658static PyObject *
11659unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011660/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011662 Py_ssize_t i, length;
11663 int kind;
11664 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665 int cased;
11666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 if (PyUnicode_READY(self) == -1)
11668 return NULL;
11669 length = PyUnicode_GET_LENGTH(self);
11670 kind = PyUnicode_KIND(self);
11671 data = PyUnicode_DATA(self);
11672
Guido van Rossumd57fd912000-03-10 22:53:23 +000011673 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (length == 1)
11675 return PyBool_FromLong(
11676 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011677
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011678 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011679 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011680 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011681
Guido van Rossumd57fd912000-03-10 22:53:23 +000011682 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011683 for (i = 0; i < length; i++) {
11684 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011685
Benjamin Peterson29060642009-01-31 22:14:21 +000011686 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011687 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011688 else if (!cased && Py_UNICODE_ISLOWER(ch))
11689 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011691 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692}
11693
INADA Naoki3ae20562017-01-16 20:41:20 +090011694/*[clinic input]
11695str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696
INADA Naoki3ae20562017-01-16 20:41:20 +090011697Return True if the string is an uppercase string, False otherwise.
11698
11699A string is uppercase if all cased characters in the string are uppercase and
11700there is at least one cased character in the string.
11701[clinic start generated code]*/
11702
11703static PyObject *
11704unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011705/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707 Py_ssize_t i, length;
11708 int kind;
11709 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710 int cased;
11711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 if (PyUnicode_READY(self) == -1)
11713 return NULL;
11714 length = PyUnicode_GET_LENGTH(self);
11715 kind = PyUnicode_KIND(self);
11716 data = PyUnicode_DATA(self);
11717
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 if (length == 1)
11720 return PyBool_FromLong(
11721 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011723 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011725 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011726
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 for (i = 0; i < length; i++) {
11729 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011730
Benjamin Peterson29060642009-01-31 22:14:21 +000011731 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011732 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011733 else if (!cased && Py_UNICODE_ISUPPER(ch))
11734 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011736 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737}
11738
INADA Naoki3ae20562017-01-16 20:41:20 +090011739/*[clinic input]
11740str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741
INADA Naoki3ae20562017-01-16 20:41:20 +090011742Return True if the string is a title-cased string, False otherwise.
11743
11744In a title-cased string, upper- and title-case characters may only
11745follow uncased characters and lowercase characters only cased ones.
11746[clinic start generated code]*/
11747
11748static PyObject *
11749unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011750/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011752 Py_ssize_t i, length;
11753 int kind;
11754 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755 int cased, previous_is_cased;
11756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757 if (PyUnicode_READY(self) == -1)
11758 return NULL;
11759 length = PyUnicode_GET_LENGTH(self);
11760 kind = PyUnicode_KIND(self);
11761 data = PyUnicode_DATA(self);
11762
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011764 if (length == 1) {
11765 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11766 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11767 (Py_UNICODE_ISUPPER(ch) != 0));
11768 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011770 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011772 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011773
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774 cased = 0;
11775 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776 for (i = 0; i < length; i++) {
11777 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011778
Benjamin Peterson29060642009-01-31 22:14:21 +000011779 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11780 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011781 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011782 previous_is_cased = 1;
11783 cased = 1;
11784 }
11785 else if (Py_UNICODE_ISLOWER(ch)) {
11786 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011787 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011788 previous_is_cased = 1;
11789 cased = 1;
11790 }
11791 else
11792 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011793 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011794 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795}
11796
INADA Naoki3ae20562017-01-16 20:41:20 +090011797/*[clinic input]
11798str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011799
INADA Naoki3ae20562017-01-16 20:41:20 +090011800Return True if the string is a whitespace string, False otherwise.
11801
11802A string is whitespace if all characters in the string are whitespace and there
11803is at least one character in the string.
11804[clinic start generated code]*/
11805
11806static PyObject *
11807unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011808/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 Py_ssize_t i, length;
11811 int kind;
11812 void *data;
11813
11814 if (PyUnicode_READY(self) == -1)
11815 return NULL;
11816 length = PyUnicode_GET_LENGTH(self);
11817 kind = PyUnicode_KIND(self);
11818 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011819
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 if (length == 1)
11822 return PyBool_FromLong(
11823 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011824
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011825 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011827 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011829 for (i = 0; i < length; i++) {
11830 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011831 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011832 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011834 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011835}
11836
INADA Naoki3ae20562017-01-16 20:41:20 +090011837/*[clinic input]
11838str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011839
INADA Naoki3ae20562017-01-16 20:41:20 +090011840Return True if the string is an alphabetic string, False otherwise.
11841
11842A string is alphabetic if all characters in the string are alphabetic and there
11843is at least one character in the string.
11844[clinic start generated code]*/
11845
11846static PyObject *
11847unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011848/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011849{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011850 Py_ssize_t i, length;
11851 int kind;
11852 void *data;
11853
11854 if (PyUnicode_READY(self) == -1)
11855 return NULL;
11856 length = PyUnicode_GET_LENGTH(self);
11857 kind = PyUnicode_KIND(self);
11858 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011859
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011860 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011861 if (length == 1)
11862 return PyBool_FromLong(
11863 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011864
11865 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011866 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011867 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011868
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011869 for (i = 0; i < length; i++) {
11870 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011871 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011872 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011873 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011874}
11875
INADA Naoki3ae20562017-01-16 20:41:20 +090011876/*[clinic input]
11877str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011878
INADA Naoki3ae20562017-01-16 20:41:20 +090011879Return True if the string is an alpha-numeric string, False otherwise.
11880
11881A string is alpha-numeric if all characters in the string are alpha-numeric and
11882there is at least one character in the string.
11883[clinic start generated code]*/
11884
11885static PyObject *
11886unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011887/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011889 int kind;
11890 void *data;
11891 Py_ssize_t len, i;
11892
11893 if (PyUnicode_READY(self) == -1)
11894 return NULL;
11895
11896 kind = PyUnicode_KIND(self);
11897 data = PyUnicode_DATA(self);
11898 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011899
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011900 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 if (len == 1) {
11902 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11903 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11904 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011905
11906 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011908 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011909
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 for (i = 0; i < len; i++) {
11911 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011912 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011913 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011914 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011915 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011916}
11917
INADA Naoki3ae20562017-01-16 20:41:20 +090011918/*[clinic input]
11919str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920
INADA Naoki3ae20562017-01-16 20:41:20 +090011921Return True if the string is a decimal string, False otherwise.
11922
11923A string is a decimal string if all characters in the string are decimal and
11924there is at least one character in the string.
11925[clinic start generated code]*/
11926
11927static PyObject *
11928unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011929/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011931 Py_ssize_t i, length;
11932 int kind;
11933 void *data;
11934
11935 if (PyUnicode_READY(self) == -1)
11936 return NULL;
11937 length = PyUnicode_GET_LENGTH(self);
11938 kind = PyUnicode_KIND(self);
11939 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940
Guido van Rossumd57fd912000-03-10 22:53:23 +000011941 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011942 if (length == 1)
11943 return PyBool_FromLong(
11944 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011946 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011948 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 for (i = 0; i < length; i++) {
11951 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011952 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011954 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955}
11956
INADA Naoki3ae20562017-01-16 20:41:20 +090011957/*[clinic input]
11958str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959
INADA Naoki3ae20562017-01-16 20:41:20 +090011960Return True if the string is a digit string, False otherwise.
11961
11962A string is a digit string if all characters in the string are digits and there
11963is at least one character in the string.
11964[clinic start generated code]*/
11965
11966static PyObject *
11967unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011968/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 Py_ssize_t i, length;
11971 int kind;
11972 void *data;
11973
11974 if (PyUnicode_READY(self) == -1)
11975 return NULL;
11976 length = PyUnicode_GET_LENGTH(self);
11977 kind = PyUnicode_KIND(self);
11978 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 if (length == 1) {
11982 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11983 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11984 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011985
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011986 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011987 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011988 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011989
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 for (i = 0; i < length; i++) {
11991 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011992 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011994 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995}
11996
INADA Naoki3ae20562017-01-16 20:41:20 +090011997/*[clinic input]
11998str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000011999
INADA Naoki3ae20562017-01-16 20:41:20 +090012000Return True if the string is a numeric string, False otherwise.
12001
12002A string is numeric if all characters in the string are numeric and there is at
12003least one character in the string.
12004[clinic start generated code]*/
12005
12006static PyObject *
12007unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012008/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 Py_ssize_t i, length;
12011 int kind;
12012 void *data;
12013
12014 if (PyUnicode_READY(self) == -1)
12015 return NULL;
12016 length = PyUnicode_GET_LENGTH(self);
12017 kind = PyUnicode_KIND(self);
12018 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012019
Guido van Rossumd57fd912000-03-10 22:53:23 +000012020 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 if (length == 1)
12022 return PyBool_FromLong(
12023 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012025 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012027 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 for (i = 0; i < length; i++) {
12030 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012031 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012032 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012033 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012034}
12035
Martin v. Löwis47383402007-08-15 07:32:56 +000012036int
12037PyUnicode_IsIdentifier(PyObject *self)
12038{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039 int kind;
12040 void *data;
12041 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012042 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012043
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 if (PyUnicode_READY(self) == -1) {
12045 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012046 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 }
12048
12049 /* Special case for empty strings */
12050 if (PyUnicode_GET_LENGTH(self) == 0)
12051 return 0;
12052 kind = PyUnicode_KIND(self);
12053 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012054
12055 /* PEP 3131 says that the first character must be in
12056 XID_Start and subsequent characters in XID_Continue,
12057 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012058 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012059 letters, digits, underscore). However, given the current
12060 definition of XID_Start and XID_Continue, it is sufficient
12061 to check just for these, except that _ must be allowed
12062 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012063 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012064 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012065 return 0;
12066
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012067 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012068 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012069 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012070 return 1;
12071}
12072
INADA Naoki3ae20562017-01-16 20:41:20 +090012073/*[clinic input]
12074str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012075
INADA Naoki3ae20562017-01-16 20:41:20 +090012076Return True if the string is a valid Python identifier, False otherwise.
12077
Sanyam Khuranaffc5a142018-10-08 12:23:32 +053012078Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012079such as "def" or "class".
INADA Naoki3ae20562017-01-16 20:41:20 +090012080[clinic start generated code]*/
12081
12082static PyObject *
12083unicode_isidentifier_impl(PyObject *self)
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012084/*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012085{
12086 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12087}
12088
INADA Naoki3ae20562017-01-16 20:41:20 +090012089/*[clinic input]
12090str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012091
INADA Naoki3ae20562017-01-16 20:41:20 +090012092Return True if the string is printable, False otherwise.
12093
12094A string is printable if all of its characters are considered printable in
12095repr() or if it is empty.
12096[clinic start generated code]*/
12097
12098static PyObject *
12099unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012100/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012101{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 Py_ssize_t i, length;
12103 int kind;
12104 void *data;
12105
12106 if (PyUnicode_READY(self) == -1)
12107 return NULL;
12108 length = PyUnicode_GET_LENGTH(self);
12109 kind = PyUnicode_KIND(self);
12110 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012111
12112 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012113 if (length == 1)
12114 return PyBool_FromLong(
12115 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012117 for (i = 0; i < length; i++) {
12118 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012119 Py_RETURN_FALSE;
12120 }
12121 }
12122 Py_RETURN_TRUE;
12123}
12124
INADA Naoki3ae20562017-01-16 20:41:20 +090012125/*[clinic input]
12126str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127
INADA Naoki3ae20562017-01-16 20:41:20 +090012128 iterable: object
12129 /
12130
12131Concatenate any number of strings.
12132
Martin Panter91a88662017-01-24 00:30:06 +000012133The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012134The result is returned as a new string.
12135
12136Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12137[clinic start generated code]*/
12138
12139static PyObject *
12140unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012141/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142{
INADA Naoki3ae20562017-01-16 20:41:20 +090012143 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144}
12145
Martin v. Löwis18e16552006-02-15 17:27:45 +000012146static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012147unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149 if (PyUnicode_READY(self) == -1)
12150 return -1;
12151 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152}
12153
INADA Naoki3ae20562017-01-16 20:41:20 +090012154/*[clinic input]
12155str.ljust as unicode_ljust
12156
12157 width: Py_ssize_t
12158 fillchar: Py_UCS4 = ' '
12159 /
12160
12161Return a left-justified string of length width.
12162
12163Padding is done using the specified fill character (default is a space).
12164[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165
12166static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012167unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12168/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012170 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012171 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172
Victor Stinnerc4b49542011-12-11 22:44:26 +010012173 if (PyUnicode_GET_LENGTH(self) >= width)
12174 return unicode_result_unchanged(self);
12175
12176 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177}
12178
INADA Naoki3ae20562017-01-16 20:41:20 +090012179/*[clinic input]
12180str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
INADA Naoki3ae20562017-01-16 20:41:20 +090012182Return a copy of the string converted to lowercase.
12183[clinic start generated code]*/
12184
12185static PyObject *
12186unicode_lower_impl(PyObject *self)
12187/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012189 if (PyUnicode_READY(self) == -1)
12190 return NULL;
12191 if (PyUnicode_IS_ASCII(self))
12192 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012193 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012194}
12195
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012196#define LEFTSTRIP 0
12197#define RIGHTSTRIP 1
12198#define BOTHSTRIP 2
12199
12200/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012201static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012202
INADA Naoki3ae20562017-01-16 20:41:20 +090012203#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012204
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012205/* externally visible for str.strip(unicode) */
12206PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012207_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012208{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012209 void *data;
12210 int kind;
12211 Py_ssize_t i, j, len;
12212 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012213 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012214
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012215 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12216 return NULL;
12217
12218 kind = PyUnicode_KIND(self);
12219 data = PyUnicode_DATA(self);
12220 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012221 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12223 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012224 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012225
Benjamin Peterson14339b62009-01-31 16:36:08 +000012226 i = 0;
12227 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012228 while (i < len) {
12229 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12230 if (!BLOOM(sepmask, ch))
12231 break;
12232 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12233 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012234 i++;
12235 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012236 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012237
Benjamin Peterson14339b62009-01-31 16:36:08 +000012238 j = len;
12239 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012240 j--;
12241 while (j >= i) {
12242 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12243 if (!BLOOM(sepmask, ch))
12244 break;
12245 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12246 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012247 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012248 }
12249
Benjamin Peterson29060642009-01-31 22:14:21 +000012250 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012251 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012252
Victor Stinner7931d9a2011-11-04 00:22:48 +010012253 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254}
12255
12256PyObject*
12257PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12258{
12259 unsigned char *data;
12260 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012261 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262
Victor Stinnerde636f32011-10-01 03:55:54 +020012263 if (PyUnicode_READY(self) == -1)
12264 return NULL;
12265
Victor Stinner684d5fd2012-05-03 02:32:34 +020012266 length = PyUnicode_GET_LENGTH(self);
12267 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012268
Victor Stinner684d5fd2012-05-03 02:32:34 +020012269 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012270 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012271
Victor Stinnerde636f32011-10-01 03:55:54 +020012272 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012273 PyErr_SetString(PyExc_IndexError, "string index out of range");
12274 return NULL;
12275 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012276 if (start >= length || end < start)
12277 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012278
Victor Stinner684d5fd2012-05-03 02:32:34 +020012279 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012280 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012281 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012282 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012283 }
12284 else {
12285 kind = PyUnicode_KIND(self);
12286 data = PyUnicode_1BYTE_DATA(self);
12287 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012288 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012289 length);
12290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012291}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292
12293static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012294do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012296 Py_ssize_t len, i, j;
12297
12298 if (PyUnicode_READY(self) == -1)
12299 return NULL;
12300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012301 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012302
Victor Stinnercc7af722013-04-09 22:39:24 +020012303 if (PyUnicode_IS_ASCII(self)) {
12304 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12305
12306 i = 0;
12307 if (striptype != RIGHTSTRIP) {
12308 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012309 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012310 if (!_Py_ascii_whitespace[ch])
12311 break;
12312 i++;
12313 }
12314 }
12315
12316 j = len;
12317 if (striptype != LEFTSTRIP) {
12318 j--;
12319 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012320 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012321 if (!_Py_ascii_whitespace[ch])
12322 break;
12323 j--;
12324 }
12325 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012326 }
12327 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012328 else {
12329 int kind = PyUnicode_KIND(self);
12330 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012331
Victor Stinnercc7af722013-04-09 22:39:24 +020012332 i = 0;
12333 if (striptype != RIGHTSTRIP) {
12334 while (i < len) {
12335 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12336 if (!Py_UNICODE_ISSPACE(ch))
12337 break;
12338 i++;
12339 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012340 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012341
12342 j = len;
12343 if (striptype != LEFTSTRIP) {
12344 j--;
12345 while (j >= i) {
12346 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12347 if (!Py_UNICODE_ISSPACE(ch))
12348 break;
12349 j--;
12350 }
12351 j++;
12352 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012353 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012354
Victor Stinner7931d9a2011-11-04 00:22:48 +010012355 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012356}
12357
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012358
12359static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012360do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012361{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012362 if (sep != NULL && sep != Py_None) {
12363 if (PyUnicode_Check(sep))
12364 return _PyUnicode_XStrip(self, striptype, sep);
12365 else {
12366 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012367 "%s arg must be None or str",
12368 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012369 return NULL;
12370 }
12371 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012372
Benjamin Peterson14339b62009-01-31 16:36:08 +000012373 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012374}
12375
12376
INADA Naoki3ae20562017-01-16 20:41:20 +090012377/*[clinic input]
12378str.strip as unicode_strip
12379
12380 chars: object = None
12381 /
12382
Victor Stinner0c4a8282017-01-17 02:21:47 +010012383Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012384
12385If chars is given and not None, remove characters in chars instead.
12386[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012387
12388static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012389unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012390/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012391{
INADA Naoki3ae20562017-01-16 20:41:20 +090012392 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012393}
12394
12395
INADA Naoki3ae20562017-01-16 20:41:20 +090012396/*[clinic input]
12397str.lstrip as unicode_lstrip
12398
12399 chars: object = NULL
12400 /
12401
12402Return a copy of the string with leading whitespace removed.
12403
12404If chars is given and not None, remove characters in chars instead.
12405[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012406
12407static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012408unicode_lstrip_impl(PyObject *self, PyObject *chars)
12409/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012410{
INADA Naoki3ae20562017-01-16 20:41:20 +090012411 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012412}
12413
12414
INADA Naoki3ae20562017-01-16 20:41:20 +090012415/*[clinic input]
12416str.rstrip as unicode_rstrip
12417
12418 chars: object = NULL
12419 /
12420
12421Return a copy of the string with trailing whitespace removed.
12422
12423If chars is given and not None, remove characters in chars instead.
12424[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012425
12426static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012427unicode_rstrip_impl(PyObject *self, PyObject *chars)
12428/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012429{
INADA Naoki3ae20562017-01-16 20:41:20 +090012430 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012431}
12432
12433
Guido van Rossumd57fd912000-03-10 22:53:23 +000012434static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012435unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012436{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012437 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012438 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012439
Serhiy Storchaka05997252013-01-26 12:14:02 +020012440 if (len < 1)
12441 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012442
Victor Stinnerc4b49542011-12-11 22:44:26 +010012443 /* no repeat, return original string */
12444 if (len == 1)
12445 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012446
Benjamin Petersonbac79492012-01-14 13:34:47 -050012447 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012448 return NULL;
12449
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012450 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012451 PyErr_SetString(PyExc_OverflowError,
12452 "repeated string is too long");
12453 return NULL;
12454 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012455 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012456
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012457 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012458 if (!u)
12459 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012460 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 if (PyUnicode_GET_LENGTH(str) == 1) {
12463 const int kind = PyUnicode_KIND(str);
12464 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012465 if (kind == PyUnicode_1BYTE_KIND) {
12466 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012467 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012468 }
12469 else if (kind == PyUnicode_2BYTE_KIND) {
12470 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012471 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012472 ucs2[n] = fill_char;
12473 } else {
12474 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12475 assert(kind == PyUnicode_4BYTE_KIND);
12476 for (n = 0; n < len; ++n)
12477 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012478 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012479 }
12480 else {
12481 /* number of characters copied this far */
12482 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012483 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012484 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012485 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012487 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012489 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012490 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012491 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492 }
12493
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012494 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012495 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496}
12497
Alexander Belopolsky40018472011-02-26 01:02:56 +000012498PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012499PyUnicode_Replace(PyObject *str,
12500 PyObject *substr,
12501 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012502 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012504 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12505 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012506 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012507 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012508}
12509
INADA Naoki3ae20562017-01-16 20:41:20 +090012510/*[clinic input]
12511str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012512
INADA Naoki3ae20562017-01-16 20:41:20 +090012513 old: unicode
12514 new: unicode
12515 count: Py_ssize_t = -1
12516 Maximum number of occurrences to replace.
12517 -1 (the default value) means replace all occurrences.
12518 /
12519
12520Return a copy with all occurrences of substring old replaced by new.
12521
12522If the optional argument count is given, only the first count occurrences are
12523replaced.
12524[clinic start generated code]*/
12525
12526static PyObject *
12527unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12528 Py_ssize_t count)
12529/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012530{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012531 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012532 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012533 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534}
12535
Alexander Belopolsky40018472011-02-26 01:02:56 +000012536static PyObject *
12537unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012538{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012539 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012540 Py_ssize_t isize;
12541 Py_ssize_t osize, squote, dquote, i, o;
12542 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012543 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012547 return NULL;
12548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 isize = PyUnicode_GET_LENGTH(unicode);
12550 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 /* Compute length of output, quote characters, and
12553 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012554 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 max = 127;
12556 squote = dquote = 0;
12557 ikind = PyUnicode_KIND(unicode);
12558 for (i = 0; i < isize; i++) {
12559 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012560 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012562 case '\'': squote++; break;
12563 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012565 incr = 2;
12566 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012567 default:
12568 /* Fast-path ASCII */
12569 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012570 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012572 ;
12573 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012576 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012577 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012578 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012580 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012582 if (osize > PY_SSIZE_T_MAX - incr) {
12583 PyErr_SetString(PyExc_OverflowError,
12584 "string is too long to generate repr");
12585 return NULL;
12586 }
12587 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 }
12589
12590 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012591 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012592 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012593 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012594 if (dquote)
12595 /* Both squote and dquote present. Use squote,
12596 and escape them */
12597 osize += squote;
12598 else
12599 quote = '"';
12600 }
Victor Stinner55c08782013-04-14 18:45:39 +020012601 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012602
12603 repr = PyUnicode_New(osize, max);
12604 if (repr == NULL)
12605 return NULL;
12606 okind = PyUnicode_KIND(repr);
12607 odata = PyUnicode_DATA(repr);
12608
12609 PyUnicode_WRITE(okind, odata, 0, quote);
12610 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012611 if (unchanged) {
12612 _PyUnicode_FastCopyCharacters(repr, 1,
12613 unicode, 0,
12614 isize);
12615 }
12616 else {
12617 for (i = 0, o = 1; i < isize; i++) {
12618 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012619
Victor Stinner55c08782013-04-14 18:45:39 +020012620 /* Escape quotes and backslashes */
12621 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012622 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012624 continue;
12625 }
12626
12627 /* Map special whitespace to '\t', \n', '\r' */
12628 if (ch == '\t') {
12629 PyUnicode_WRITE(okind, odata, o++, '\\');
12630 PyUnicode_WRITE(okind, odata, o++, 't');
12631 }
12632 else if (ch == '\n') {
12633 PyUnicode_WRITE(okind, odata, o++, '\\');
12634 PyUnicode_WRITE(okind, odata, o++, 'n');
12635 }
12636 else if (ch == '\r') {
12637 PyUnicode_WRITE(okind, odata, o++, '\\');
12638 PyUnicode_WRITE(okind, odata, o++, 'r');
12639 }
12640
12641 /* Map non-printable US ASCII to '\xhh' */
12642 else if (ch < ' ' || ch == 0x7F) {
12643 PyUnicode_WRITE(okind, odata, o++, '\\');
12644 PyUnicode_WRITE(okind, odata, o++, 'x');
12645 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12646 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12647 }
12648
12649 /* Copy ASCII characters as-is */
12650 else if (ch < 0x7F) {
12651 PyUnicode_WRITE(okind, odata, o++, ch);
12652 }
12653
12654 /* Non-ASCII characters */
12655 else {
12656 /* Map Unicode whitespace and control characters
12657 (categories Z* and C* except ASCII space)
12658 */
12659 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12660 PyUnicode_WRITE(okind, odata, o++, '\\');
12661 /* Map 8-bit characters to '\xhh' */
12662 if (ch <= 0xff) {
12663 PyUnicode_WRITE(okind, odata, o++, 'x');
12664 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12665 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12666 }
12667 /* Map 16-bit characters to '\uxxxx' */
12668 else if (ch <= 0xffff) {
12669 PyUnicode_WRITE(okind, odata, o++, 'u');
12670 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12671 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12672 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12673 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12674 }
12675 /* Map 21-bit characters to '\U00xxxxxx' */
12676 else {
12677 PyUnicode_WRITE(okind, odata, o++, 'U');
12678 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12679 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12680 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12681 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12682 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12683 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12684 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12685 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12686 }
12687 }
12688 /* Copy characters as-is */
12689 else {
12690 PyUnicode_WRITE(okind, odata, o++, ch);
12691 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012692 }
12693 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012694 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012695 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012696 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012697 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698}
12699
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012700PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012701 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702\n\
12703Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012704such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705arguments start and end are interpreted as in slice notation.\n\
12706\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012707Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012708
12709static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012711{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012712 /* initialize variables to prevent gcc warning */
12713 PyObject *substring = NULL;
12714 Py_ssize_t start = 0;
12715 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012716 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012718 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012720
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012721 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012724 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012726 if (result == -2)
12727 return NULL;
12728
Christian Heimes217cfd12007-12-02 14:31:20 +000012729 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012730}
12731
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012732PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012733 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012735Return the highest index in S where substring sub is found,\n\
12736such that sub is contained within S[start:end]. Optional\n\
12737arguments start and end are interpreted as in slice notation.\n\
12738\n\
12739Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740
12741static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012742unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012744 /* initialize variables to prevent gcc warning */
12745 PyObject *substring = NULL;
12746 Py_ssize_t start = 0;
12747 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012748 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012750 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012751 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012753 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012754 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012755
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012756 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012757
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012758 if (result == -2)
12759 return NULL;
12760
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761 if (result < 0) {
12762 PyErr_SetString(PyExc_ValueError, "substring not found");
12763 return NULL;
12764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765
Christian Heimes217cfd12007-12-02 14:31:20 +000012766 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767}
12768
INADA Naoki3ae20562017-01-16 20:41:20 +090012769/*[clinic input]
12770str.rjust as unicode_rjust
12771
12772 width: Py_ssize_t
12773 fillchar: Py_UCS4 = ' '
12774 /
12775
12776Return a right-justified string of length width.
12777
12778Padding is done using the specified fill character (default is a space).
12779[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780
12781static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012782unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12783/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012785 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786 return NULL;
12787
Victor Stinnerc4b49542011-12-11 22:44:26 +010012788 if (PyUnicode_GET_LENGTH(self) >= width)
12789 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790
Victor Stinnerc4b49542011-12-11 22:44:26 +010012791 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012792}
12793
Alexander Belopolsky40018472011-02-26 01:02:56 +000012794PyObject *
12795PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012797 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012798 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012800 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801}
12802
INADA Naoki3ae20562017-01-16 20:41:20 +090012803/*[clinic input]
12804str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805
INADA Naoki3ae20562017-01-16 20:41:20 +090012806 sep: object = None
12807 The delimiter according which to split the string.
12808 None (the default value) means split according to any whitespace,
12809 and discard empty strings from the result.
12810 maxsplit: Py_ssize_t = -1
12811 Maximum number of splits to do.
12812 -1 (the default value) means no limit.
12813
12814Return a list of the words in the string, using sep as the delimiter string.
12815[clinic start generated code]*/
12816
12817static PyObject *
12818unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12819/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820{
INADA Naoki3ae20562017-01-16 20:41:20 +090012821 if (sep == Py_None)
12822 return split(self, NULL, maxsplit);
12823 if (PyUnicode_Check(sep))
12824 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012825
Victor Stinner998b8062018-09-12 00:23:25 +020012826 PyErr_Format(PyExc_TypeError,
12827 "must be str or None, not %.100s",
12828 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012829 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830}
12831
Thomas Wouters477c8d52006-05-27 19:21:47 +000012832PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012833PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012834{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012835 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012836 int kind1, kind2;
12837 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012838 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012839
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012840 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012841 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012842
Victor Stinner14f8f022011-10-05 20:58:25 +020012843 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012844 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012845 len1 = PyUnicode_GET_LENGTH(str_obj);
12846 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012847 if (kind1 < kind2 || len1 < len2) {
12848 _Py_INCREF_UNICODE_EMPTY();
12849 if (!unicode_empty)
12850 out = NULL;
12851 else {
12852 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12853 Py_DECREF(unicode_empty);
12854 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012855 return out;
12856 }
12857 buf1 = PyUnicode_DATA(str_obj);
12858 buf2 = PyUnicode_DATA(sep_obj);
12859 if (kind2 != kind1) {
12860 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12861 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012862 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012863 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012864
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012865 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012866 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012867 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12868 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12869 else
12870 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012871 break;
12872 case PyUnicode_2BYTE_KIND:
12873 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12874 break;
12875 case PyUnicode_4BYTE_KIND:
12876 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12877 break;
12878 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012879 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012880 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012881
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012882 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012883 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012884
12885 return out;
12886}
12887
12888
12889PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012890PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012891{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012892 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012893 int kind1, kind2;
12894 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012895 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012896
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012897 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012898 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012899
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012900 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012901 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 len1 = PyUnicode_GET_LENGTH(str_obj);
12903 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012904 if (kind1 < kind2 || len1 < len2) {
12905 _Py_INCREF_UNICODE_EMPTY();
12906 if (!unicode_empty)
12907 out = NULL;
12908 else {
12909 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12910 Py_DECREF(unicode_empty);
12911 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012912 return out;
12913 }
12914 buf1 = PyUnicode_DATA(str_obj);
12915 buf2 = PyUnicode_DATA(sep_obj);
12916 if (kind2 != kind1) {
12917 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12918 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012919 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012920 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012921
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012922 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012923 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012924 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12925 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12926 else
12927 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012928 break;
12929 case PyUnicode_2BYTE_KIND:
12930 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12931 break;
12932 case PyUnicode_4BYTE_KIND:
12933 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12934 break;
12935 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012936 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012937 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012938
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012939 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012940 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012941
12942 return out;
12943}
12944
INADA Naoki3ae20562017-01-16 20:41:20 +090012945/*[clinic input]
12946str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012947
INADA Naoki3ae20562017-01-16 20:41:20 +090012948 sep: object
12949 /
12950
12951Partition the string into three parts using the given separator.
12952
12953This will search for the separator in the string. If the separator is found,
12954returns a 3-tuple containing the part before the separator, the separator
12955itself, and the part after it.
12956
12957If the separator is not found, returns a 3-tuple containing the original string
12958and two empty strings.
12959[clinic start generated code]*/
12960
12961static PyObject *
12962unicode_partition(PyObject *self, PyObject *sep)
12963/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012964{
INADA Naoki3ae20562017-01-16 20:41:20 +090012965 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012966}
12967
INADA Naoki3ae20562017-01-16 20:41:20 +090012968/*[clinic input]
12969str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012970
INADA Naoki3ae20562017-01-16 20:41:20 +090012971Partition the string into three parts using the given separator.
12972
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012973This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012974the separator is found, returns a 3-tuple containing the part before the
12975separator, the separator itself, and the part after it.
12976
12977If the separator is not found, returns a 3-tuple containing two empty strings
12978and the original string.
12979[clinic start generated code]*/
12980
12981static PyObject *
12982unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012983/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012984{
INADA Naoki3ae20562017-01-16 20:41:20 +090012985 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012986}
12987
Alexander Belopolsky40018472011-02-26 01:02:56 +000012988PyObject *
12989PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012990{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012991 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012992 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012993
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012994 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012995}
12996
INADA Naoki3ae20562017-01-16 20:41:20 +090012997/*[clinic input]
12998str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012999
INADA Naoki3ae20562017-01-16 20:41:20 +090013000Return a list of the words in the string, using sep as the delimiter string.
13001
13002Splits are done starting at the end of the string and working to the front.
13003[clinic start generated code]*/
13004
13005static PyObject *
13006unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13007/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013008{
INADA Naoki3ae20562017-01-16 20:41:20 +090013009 if (sep == Py_None)
13010 return rsplit(self, NULL, maxsplit);
13011 if (PyUnicode_Check(sep))
13012 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013013
Victor Stinner998b8062018-09-12 00:23:25 +020013014 PyErr_Format(PyExc_TypeError,
13015 "must be str or None, not %.100s",
13016 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013017 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013018}
13019
INADA Naoki3ae20562017-01-16 20:41:20 +090013020/*[clinic input]
13021str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013022
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013023 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013024
13025Return a list of the lines in the string, breaking at line boundaries.
13026
13027Line breaks are not included in the resulting list unless keepends is given and
13028true.
13029[clinic start generated code]*/
13030
13031static PyObject *
13032unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013033/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013034{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013035 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013036}
13037
13038static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013039PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013040{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013041 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042}
13043
INADA Naoki3ae20562017-01-16 20:41:20 +090013044/*[clinic input]
13045str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013046
INADA Naoki3ae20562017-01-16 20:41:20 +090013047Convert uppercase characters to lowercase and lowercase characters to uppercase.
13048[clinic start generated code]*/
13049
13050static PyObject *
13051unicode_swapcase_impl(PyObject *self)
13052/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013053{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013054 if (PyUnicode_READY(self) == -1)
13055 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013056 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057}
13058
Larry Hastings61272b72014-01-07 12:41:53 -080013059/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013060
Larry Hastings31826802013-10-19 00:09:25 -070013061@staticmethod
13062str.maketrans as unicode_maketrans
13063
13064 x: object
13065
13066 y: unicode=NULL
13067
13068 z: unicode=NULL
13069
13070 /
13071
13072Return a translation table usable for str.translate().
13073
13074If there is only one argument, it must be a dictionary mapping Unicode
13075ordinals (integers) or characters to Unicode ordinals, strings or None.
13076Character keys will be then converted to ordinals.
13077If there are two arguments, they must be strings of equal length, and
13078in the resulting dictionary, each character in x will be mapped to the
13079character at the same position in y. If there is a third argument, it
13080must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013081[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013082
Larry Hastings31826802013-10-19 00:09:25 -070013083static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013084unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013085/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013086{
Georg Brandlceee0772007-11-27 23:48:05 +000013087 PyObject *new = NULL, *key, *value;
13088 Py_ssize_t i = 0;
13089 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013090
Georg Brandlceee0772007-11-27 23:48:05 +000013091 new = PyDict_New();
13092 if (!new)
13093 return NULL;
13094 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013095 int x_kind, y_kind, z_kind;
13096 void *x_data, *y_data, *z_data;
13097
Georg Brandlceee0772007-11-27 23:48:05 +000013098 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013099 if (!PyUnicode_Check(x)) {
13100 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13101 "be a string if there is a second argument");
13102 goto err;
13103 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013105 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13106 "arguments must have equal length");
13107 goto err;
13108 }
13109 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013110 x_kind = PyUnicode_KIND(x);
13111 y_kind = PyUnicode_KIND(y);
13112 x_data = PyUnicode_DATA(x);
13113 y_data = PyUnicode_DATA(y);
13114 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13115 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013116 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013117 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013118 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013119 if (!value) {
13120 Py_DECREF(key);
13121 goto err;
13122 }
Georg Brandlceee0772007-11-27 23:48:05 +000013123 res = PyDict_SetItem(new, key, value);
13124 Py_DECREF(key);
13125 Py_DECREF(value);
13126 if (res < 0)
13127 goto err;
13128 }
13129 /* create entries for deleting chars in z */
13130 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013131 z_kind = PyUnicode_KIND(z);
13132 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013133 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013134 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013135 if (!key)
13136 goto err;
13137 res = PyDict_SetItem(new, key, Py_None);
13138 Py_DECREF(key);
13139 if (res < 0)
13140 goto err;
13141 }
13142 }
13143 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 int kind;
13145 void *data;
13146
Georg Brandlceee0772007-11-27 23:48:05 +000013147 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013148 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013149 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13150 "to maketrans it must be a dict");
13151 goto err;
13152 }
13153 /* copy entries into the new dict, converting string keys to int keys */
13154 while (PyDict_Next(x, &i, &key, &value)) {
13155 if (PyUnicode_Check(key)) {
13156 /* convert string keys to integer keys */
13157 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013158 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013159 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13160 "table must be of length 1");
13161 goto err;
13162 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013163 kind = PyUnicode_KIND(key);
13164 data = PyUnicode_DATA(key);
13165 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013166 if (!newkey)
13167 goto err;
13168 res = PyDict_SetItem(new, newkey, value);
13169 Py_DECREF(newkey);
13170 if (res < 0)
13171 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013172 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013173 /* just keep integer keys */
13174 if (PyDict_SetItem(new, key, value) < 0)
13175 goto err;
13176 } else {
13177 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13178 "be strings or integers");
13179 goto err;
13180 }
13181 }
13182 }
13183 return new;
13184 err:
13185 Py_DECREF(new);
13186 return NULL;
13187}
13188
INADA Naoki3ae20562017-01-16 20:41:20 +090013189/*[clinic input]
13190str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191
INADA Naoki3ae20562017-01-16 20:41:20 +090013192 table: object
13193 Translation table, which must be a mapping of Unicode ordinals to
13194 Unicode ordinals, strings, or None.
13195 /
13196
13197Replace each character in the string using the given translation table.
13198
13199The table must implement lookup/indexing via __getitem__, for instance a
13200dictionary or list. If this operation raises LookupError, the character is
13201left untouched. Characters mapped to None are deleted.
13202[clinic start generated code]*/
13203
13204static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013205unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013206/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013208 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209}
13210
INADA Naoki3ae20562017-01-16 20:41:20 +090013211/*[clinic input]
13212str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213
INADA Naoki3ae20562017-01-16 20:41:20 +090013214Return a copy of the string converted to uppercase.
13215[clinic start generated code]*/
13216
13217static PyObject *
13218unicode_upper_impl(PyObject *self)
13219/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013221 if (PyUnicode_READY(self) == -1)
13222 return NULL;
13223 if (PyUnicode_IS_ASCII(self))
13224 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013225 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013226}
13227
INADA Naoki3ae20562017-01-16 20:41:20 +090013228/*[clinic input]
13229str.zfill as unicode_zfill
13230
13231 width: Py_ssize_t
13232 /
13233
13234Pad a numeric string with zeros on the left, to fill a field of the given width.
13235
13236The string is never truncated.
13237[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013238
13239static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013240unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013241/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013242{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013243 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013244 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013245 int kind;
13246 void *data;
13247 Py_UCS4 chr;
13248
Benjamin Petersonbac79492012-01-14 13:34:47 -050013249 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013250 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251
Victor Stinnerc4b49542011-12-11 22:44:26 +010013252 if (PyUnicode_GET_LENGTH(self) >= width)
13253 return unicode_result_unchanged(self);
13254
13255 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256
13257 u = pad(self, fill, 0, '0');
13258
Walter Dörwald068325e2002-04-15 13:36:47 +000013259 if (u == NULL)
13260 return NULL;
13261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013262 kind = PyUnicode_KIND(u);
13263 data = PyUnicode_DATA(u);
13264 chr = PyUnicode_READ(kind, data, fill);
13265
13266 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013268 PyUnicode_WRITE(kind, data, 0, chr);
13269 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270 }
13271
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013272 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013273 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013274}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275
13276#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013277static PyObject *
13278unicode__decimal2ascii(PyObject *self)
13279{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013280 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013281}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013282#endif
13283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013284PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013285 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013286\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013287Return True if S starts with the specified prefix, False otherwise.\n\
13288With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013289With optional end, stop comparing S at that position.\n\
13290prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291
13292static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013293unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013295{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013296 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013297 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013298 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013299 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013300 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013301
Jesus Ceaac451502011-04-20 17:09:23 +020013302 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013303 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013304 if (PyTuple_Check(subobj)) {
13305 Py_ssize_t i;
13306 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013307 substring = PyTuple_GET_ITEM(subobj, i);
13308 if (!PyUnicode_Check(substring)) {
13309 PyErr_Format(PyExc_TypeError,
13310 "tuple for startswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013311 "not %.100s",
13312 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013313 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013314 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013315 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013316 if (result == -1)
13317 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013318 if (result) {
13319 Py_RETURN_TRUE;
13320 }
13321 }
13322 /* nothing matched */
13323 Py_RETURN_FALSE;
13324 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013325 if (!PyUnicode_Check(subobj)) {
13326 PyErr_Format(PyExc_TypeError,
13327 "startswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013328 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013329 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013330 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013331 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013332 if (result == -1)
13333 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013334 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013335}
13336
13337
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013338PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013339 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013340\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013341Return True if S ends with the specified suffix, False otherwise.\n\
13342With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013343With optional end, stop comparing S at that position.\n\
13344suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345
13346static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013347unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013348 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013349{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013350 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013351 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013352 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013353 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013354 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013355
Jesus Ceaac451502011-04-20 17:09:23 +020013356 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013357 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013358 if (PyTuple_Check(subobj)) {
13359 Py_ssize_t i;
13360 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013361 substring = PyTuple_GET_ITEM(subobj, i);
13362 if (!PyUnicode_Check(substring)) {
13363 PyErr_Format(PyExc_TypeError,
13364 "tuple for endswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013365 "not %.100s",
13366 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013367 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013368 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013369 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013370 if (result == -1)
13371 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013372 if (result) {
13373 Py_RETURN_TRUE;
13374 }
13375 }
13376 Py_RETURN_FALSE;
13377 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013378 if (!PyUnicode_Check(subobj)) {
13379 PyErr_Format(PyExc_TypeError,
13380 "endswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013381 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013382 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013383 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013384 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013385 if (result == -1)
13386 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013387 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013388}
13389
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013390static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013391_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013392{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013393 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13394 writer->data = PyUnicode_DATA(writer->buffer);
13395
13396 if (!writer->readonly) {
13397 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013398 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013399 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013400 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013401 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13402 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13403 writer->kind = PyUnicode_WCHAR_KIND;
13404 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13405
Victor Stinner8f674cc2013-04-17 23:02:17 +020013406 /* Copy-on-write mode: set buffer size to 0 so
13407 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13408 * next write. */
13409 writer->size = 0;
13410 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013411}
13412
Victor Stinnerd3f08822012-05-29 12:57:52 +020013413void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013414_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013415{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013416 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013417
13418 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013419 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013420
13421 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13422 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13423 writer->kind = PyUnicode_WCHAR_KIND;
13424 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013425}
13426
Victor Stinnerd3f08822012-05-29 12:57:52 +020013427int
13428_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13429 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013430{
13431 Py_ssize_t newlen;
13432 PyObject *newbuffer;
13433
Victor Stinner2740e462016-09-06 16:58:36 -070013434 assert(maxchar <= MAX_UNICODE);
13435
Victor Stinnerca9381e2015-09-22 00:58:32 +020013436 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013437 assert((maxchar > writer->maxchar && length >= 0)
13438 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013439
Victor Stinner202fdca2012-05-07 12:47:02 +020013440 if (length > PY_SSIZE_T_MAX - writer->pos) {
13441 PyErr_NoMemory();
13442 return -1;
13443 }
13444 newlen = writer->pos + length;
13445
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013446 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013447
Victor Stinnerd3f08822012-05-29 12:57:52 +020013448 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013449 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013450 if (writer->overallocate
13451 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13452 /* overallocate to limit the number of realloc() */
13453 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013454 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013455 if (newlen < writer->min_length)
13456 newlen = writer->min_length;
13457
Victor Stinnerd3f08822012-05-29 12:57:52 +020013458 writer->buffer = PyUnicode_New(newlen, maxchar);
13459 if (writer->buffer == NULL)
13460 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013461 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013462 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013463 if (writer->overallocate
13464 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13465 /* overallocate to limit the number of realloc() */
13466 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013467 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013468 if (newlen < writer->min_length)
13469 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013470
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013471 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013472 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013473 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013474 newbuffer = PyUnicode_New(newlen, maxchar);
13475 if (newbuffer == NULL)
13476 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013477 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13478 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013479 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013480 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013481 }
13482 else {
13483 newbuffer = resize_compact(writer->buffer, newlen);
13484 if (newbuffer == NULL)
13485 return -1;
13486 }
13487 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013488 }
13489 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013490 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013491 newbuffer = PyUnicode_New(writer->size, maxchar);
13492 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013493 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013494 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13495 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013496 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013497 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013498 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013499 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013500
13501#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013502}
13503
Victor Stinnerca9381e2015-09-22 00:58:32 +020013504int
13505_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13506 enum PyUnicode_Kind kind)
13507{
13508 Py_UCS4 maxchar;
13509
13510 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13511 assert(writer->kind < kind);
13512
13513 switch (kind)
13514 {
13515 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13516 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13517 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13518 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013519 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013520 }
13521
13522 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13523}
13524
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013525static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013526_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013527{
Victor Stinner2740e462016-09-06 16:58:36 -070013528 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013529 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13530 return -1;
13531 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13532 writer->pos++;
13533 return 0;
13534}
13535
13536int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013537_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13538{
13539 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13540}
13541
13542int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013543_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13544{
13545 Py_UCS4 maxchar;
13546 Py_ssize_t len;
13547
13548 if (PyUnicode_READY(str) == -1)
13549 return -1;
13550 len = PyUnicode_GET_LENGTH(str);
13551 if (len == 0)
13552 return 0;
13553 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13554 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013555 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013556 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013557 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013558 Py_INCREF(str);
13559 writer->buffer = str;
13560 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013561 writer->pos += len;
13562 return 0;
13563 }
13564 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13565 return -1;
13566 }
13567 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13568 str, 0, len);
13569 writer->pos += len;
13570 return 0;
13571}
13572
Victor Stinnere215d962012-10-06 23:03:36 +020013573int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013574_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13575 Py_ssize_t start, Py_ssize_t end)
13576{
13577 Py_UCS4 maxchar;
13578 Py_ssize_t len;
13579
13580 if (PyUnicode_READY(str) == -1)
13581 return -1;
13582
13583 assert(0 <= start);
13584 assert(end <= PyUnicode_GET_LENGTH(str));
13585 assert(start <= end);
13586
13587 if (end == 0)
13588 return 0;
13589
13590 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13591 return _PyUnicodeWriter_WriteStr(writer, str);
13592
13593 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13594 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13595 else
13596 maxchar = writer->maxchar;
13597 len = end - start;
13598
13599 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13600 return -1;
13601
13602 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13603 str, start, len);
13604 writer->pos += len;
13605 return 0;
13606}
13607
13608int
Victor Stinner4a587072013-11-19 12:54:53 +010013609_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13610 const char *ascii, Py_ssize_t len)
13611{
13612 if (len == -1)
13613 len = strlen(ascii);
13614
13615 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13616
13617 if (writer->buffer == NULL && !writer->overallocate) {
13618 PyObject *str;
13619
13620 str = _PyUnicode_FromASCII(ascii, len);
13621 if (str == NULL)
13622 return -1;
13623
13624 writer->readonly = 1;
13625 writer->buffer = str;
13626 _PyUnicodeWriter_Update(writer);
13627 writer->pos += len;
13628 return 0;
13629 }
13630
13631 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13632 return -1;
13633
13634 switch (writer->kind)
13635 {
13636 case PyUnicode_1BYTE_KIND:
13637 {
13638 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13639 Py_UCS1 *data = writer->data;
13640
Christian Heimesf051e432016-09-13 20:22:02 +020013641 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013642 break;
13643 }
13644 case PyUnicode_2BYTE_KIND:
13645 {
13646 _PyUnicode_CONVERT_BYTES(
13647 Py_UCS1, Py_UCS2,
13648 ascii, ascii + len,
13649 (Py_UCS2 *)writer->data + writer->pos);
13650 break;
13651 }
13652 case PyUnicode_4BYTE_KIND:
13653 {
13654 _PyUnicode_CONVERT_BYTES(
13655 Py_UCS1, Py_UCS4,
13656 ascii, ascii + len,
13657 (Py_UCS4 *)writer->data + writer->pos);
13658 break;
13659 }
13660 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013661 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013662 }
13663
13664 writer->pos += len;
13665 return 0;
13666}
13667
13668int
13669_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13670 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013671{
13672 Py_UCS4 maxchar;
13673
13674 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13675 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13676 return -1;
13677 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13678 writer->pos += len;
13679 return 0;
13680}
13681
Victor Stinnerd3f08822012-05-29 12:57:52 +020013682PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013683_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013684{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013685 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013686
Victor Stinnerd3f08822012-05-29 12:57:52 +020013687 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013688 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013689 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013690 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013691
13692 str = writer->buffer;
13693 writer->buffer = NULL;
13694
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013695 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013696 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13697 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013698 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013699
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013700 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13701 PyObject *str2;
13702 str2 = resize_compact(str, writer->pos);
13703 if (str2 == NULL) {
13704 Py_DECREF(str);
13705 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013706 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013707 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013708 }
13709
Victor Stinner15a0bd32013-07-08 22:29:55 +020013710 assert(_PyUnicode_CheckConsistency(str, 1));
13711 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013712}
13713
Victor Stinnerd3f08822012-05-29 12:57:52 +020013714void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013715_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013716{
13717 Py_CLEAR(writer->buffer);
13718}
13719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013720#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013721
13722PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013723 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013724\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013725Return a formatted version of S, using substitutions from args and kwargs.\n\
13726The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013727
Eric Smith27bbca62010-11-04 17:06:58 +000013728PyDoc_STRVAR(format_map__doc__,
13729 "S.format_map(mapping) -> str\n\
13730\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013731Return a formatted version of S, using substitutions from mapping.\n\
13732The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013733
INADA Naoki3ae20562017-01-16 20:41:20 +090013734/*[clinic input]
13735str.__format__ as unicode___format__
13736
13737 format_spec: unicode
13738 /
13739
13740Return a formatted version of the string as described by format_spec.
13741[clinic start generated code]*/
13742
Eric Smith4a7d76d2008-05-30 18:10:19 +000013743static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013744unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013745/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013746{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013747 _PyUnicodeWriter writer;
13748 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013749
Victor Stinnerd3f08822012-05-29 12:57:52 +020013750 if (PyUnicode_READY(self) == -1)
13751 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013752 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013753 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13754 self, format_spec, 0,
13755 PyUnicode_GET_LENGTH(format_spec));
13756 if (ret == -1) {
13757 _PyUnicodeWriter_Dealloc(&writer);
13758 return NULL;
13759 }
13760 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013761}
13762
INADA Naoki3ae20562017-01-16 20:41:20 +090013763/*[clinic input]
13764str.__sizeof__ as unicode_sizeof
13765
13766Return the size of the string in memory, in bytes.
13767[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013768
13769static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013770unicode_sizeof_impl(PyObject *self)
13771/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013772{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013773 Py_ssize_t size;
13774
13775 /* If it's a compact object, account for base structure +
13776 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013777 if (PyUnicode_IS_COMPACT_ASCII(self))
13778 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13779 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013780 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013781 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013782 else {
13783 /* If it is a two-block object, account for base object, and
13784 for character block if present. */
13785 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013786 if (_PyUnicode_DATA_ANY(self))
13787 size += (PyUnicode_GET_LENGTH(self) + 1) *
13788 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013789 }
13790 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013791 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013792 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13793 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13794 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13795 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013796
13797 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013798}
13799
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013800static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013801unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013802{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013803 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013804 if (!copy)
13805 return NULL;
13806 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013807}
13808
Guido van Rossumd57fd912000-03-10 22:53:23 +000013809static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013810 UNICODE_ENCODE_METHODDEF
13811 UNICODE_REPLACE_METHODDEF
13812 UNICODE_SPLIT_METHODDEF
13813 UNICODE_RSPLIT_METHODDEF
13814 UNICODE_JOIN_METHODDEF
13815 UNICODE_CAPITALIZE_METHODDEF
13816 UNICODE_CASEFOLD_METHODDEF
13817 UNICODE_TITLE_METHODDEF
13818 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013819 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013820 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013821 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013822 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013823 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013824 UNICODE_LJUST_METHODDEF
13825 UNICODE_LOWER_METHODDEF
13826 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013827 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13828 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013829 UNICODE_RJUST_METHODDEF
13830 UNICODE_RSTRIP_METHODDEF
13831 UNICODE_RPARTITION_METHODDEF
13832 UNICODE_SPLITLINES_METHODDEF
13833 UNICODE_STRIP_METHODDEF
13834 UNICODE_SWAPCASE_METHODDEF
13835 UNICODE_TRANSLATE_METHODDEF
13836 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013837 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13838 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013839 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013840 UNICODE_ISLOWER_METHODDEF
13841 UNICODE_ISUPPER_METHODDEF
13842 UNICODE_ISTITLE_METHODDEF
13843 UNICODE_ISSPACE_METHODDEF
13844 UNICODE_ISDECIMAL_METHODDEF
13845 UNICODE_ISDIGIT_METHODDEF
13846 UNICODE_ISNUMERIC_METHODDEF
13847 UNICODE_ISALPHA_METHODDEF
13848 UNICODE_ISALNUM_METHODDEF
13849 UNICODE_ISIDENTIFIER_METHODDEF
13850 UNICODE_ISPRINTABLE_METHODDEF
13851 UNICODE_ZFILL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013852 {"format", (PyCFunction)(void(*)(void)) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013853 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013854 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013855 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013856 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013857#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013858 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013859 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013860#endif
13861
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013862 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013863 {NULL, NULL}
13864};
13865
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013866static PyObject *
13867unicode_mod(PyObject *v, PyObject *w)
13868{
Brian Curtindfc80e32011-08-10 20:28:54 -050013869 if (!PyUnicode_Check(v))
13870 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013871 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013872}
13873
13874static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013875 0, /*nb_add*/
13876 0, /*nb_subtract*/
13877 0, /*nb_multiply*/
13878 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013879};
13880
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013882 (lenfunc) unicode_length, /* sq_length */
13883 PyUnicode_Concat, /* sq_concat */
13884 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13885 (ssizeargfunc) unicode_getitem, /* sq_item */
13886 0, /* sq_slice */
13887 0, /* sq_ass_item */
13888 0, /* sq_ass_slice */
13889 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013890};
13891
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013892static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013893unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013894{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013895 if (PyUnicode_READY(self) == -1)
13896 return NULL;
13897
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013898 if (PyIndex_Check(item)) {
13899 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013900 if (i == -1 && PyErr_Occurred())
13901 return NULL;
13902 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013904 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013905 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013906 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013907 PyObject *result;
13908 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013909 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013910 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013911
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013912 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013913 return NULL;
13914 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013915 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13916 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013917
13918 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013919 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013920 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013921 slicelength == PyUnicode_GET_LENGTH(self)) {
13922 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013923 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013924 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013925 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013926 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013927 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013928 src_kind = PyUnicode_KIND(self);
13929 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013930 if (!PyUnicode_IS_ASCII(self)) {
13931 kind_limit = kind_maxchar_limit(src_kind);
13932 max_char = 0;
13933 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13934 ch = PyUnicode_READ(src_kind, src_data, cur);
13935 if (ch > max_char) {
13936 max_char = ch;
13937 if (max_char >= kind_limit)
13938 break;
13939 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013940 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013941 }
Victor Stinner55c99112011-10-13 01:17:06 +020013942 else
13943 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013944 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013945 if (result == NULL)
13946 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013947 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013948 dest_data = PyUnicode_DATA(result);
13949
13950 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013951 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13952 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013953 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013954 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013955 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013956 } else {
13957 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13958 return NULL;
13959 }
13960}
13961
13962static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013963 (lenfunc)unicode_length, /* mp_length */
13964 (binaryfunc)unicode_subscript, /* mp_subscript */
13965 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013966};
13967
Guido van Rossumd57fd912000-03-10 22:53:23 +000013968
Guido van Rossumd57fd912000-03-10 22:53:23 +000013969/* Helpers for PyUnicode_Format() */
13970
Victor Stinnera47082312012-10-04 02:19:54 +020013971struct unicode_formatter_t {
13972 PyObject *args;
13973 int args_owned;
13974 Py_ssize_t arglen, argidx;
13975 PyObject *dict;
13976
13977 enum PyUnicode_Kind fmtkind;
13978 Py_ssize_t fmtcnt, fmtpos;
13979 void *fmtdata;
13980 PyObject *fmtstr;
13981
13982 _PyUnicodeWriter writer;
13983};
13984
13985struct unicode_format_arg_t {
13986 Py_UCS4 ch;
13987 int flags;
13988 Py_ssize_t width;
13989 int prec;
13990 int sign;
13991};
13992
Guido van Rossumd57fd912000-03-10 22:53:23 +000013993static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020013994unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013995{
Victor Stinnera47082312012-10-04 02:19:54 +020013996 Py_ssize_t argidx = ctx->argidx;
13997
13998 if (argidx < ctx->arglen) {
13999 ctx->argidx++;
14000 if (ctx->arglen < 0)
14001 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014002 else
Victor Stinnera47082312012-10-04 02:19:54 +020014003 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014004 }
14005 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014006 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014007 return NULL;
14008}
14009
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014010/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014011
Victor Stinnera47082312012-10-04 02:19:54 +020014012/* Format a float into the writer if the writer is not NULL, or into *p_output
14013 otherwise.
14014
14015 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014016static int
Victor Stinnera47082312012-10-04 02:19:54 +020014017formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14018 PyObject **p_output,
14019 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014020{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014021 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014022 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014023 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014024 int prec;
14025 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014026
Guido van Rossumd57fd912000-03-10 22:53:23 +000014027 x = PyFloat_AsDouble(v);
14028 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014029 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014030
Victor Stinnera47082312012-10-04 02:19:54 +020014031 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014032 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014033 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014034
Victor Stinnera47082312012-10-04 02:19:54 +020014035 if (arg->flags & F_ALT)
14036 dtoa_flags = Py_DTSF_ALT;
14037 else
14038 dtoa_flags = 0;
14039 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014040 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014041 return -1;
14042 len = strlen(p);
14043 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014044 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014045 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014046 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014047 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014048 }
14049 else
14050 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014051 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014052 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014053}
14054
Victor Stinnerd0880d52012-04-27 23:40:13 +020014055/* formatlong() emulates the format codes d, u, o, x and X, and
14056 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14057 * Python's regular ints.
14058 * Return value: a new PyUnicodeObject*, or NULL if error.
14059 * The output string is of the form
14060 * "-"? ("0x" | "0X")? digit+
14061 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14062 * set in flags. The case of hex digits will be correct,
14063 * There will be at least prec digits, zero-filled on the left if
14064 * necessary to get that many.
14065 * val object to be converted
14066 * flags bitmask of format flags; only F_ALT is looked at
14067 * prec minimum number of digits; 0-fill on left if needed
14068 * type a character in [duoxX]; u acts the same as d
14069 *
14070 * CAUTION: o, x and X conversions on regular ints can never
14071 * produce a '-' sign, but can for Python's unbounded ints.
14072 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014073PyObject *
14074_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014075{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014076 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014077 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014078 Py_ssize_t i;
14079 int sign; /* 1 if '-', else 0 */
14080 int len; /* number of characters */
14081 Py_ssize_t llen;
14082 int numdigits; /* len == numnondigits + numdigits */
14083 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014084
Victor Stinnerd0880d52012-04-27 23:40:13 +020014085 /* Avoid exceeding SSIZE_T_MAX */
14086 if (prec > INT_MAX-3) {
14087 PyErr_SetString(PyExc_OverflowError,
14088 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014089 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014090 }
14091
14092 assert(PyLong_Check(val));
14093
14094 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014095 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014096 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014097 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014098 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014099 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014100 /* int and int subclasses should print numerically when a numeric */
14101 /* format code is used (see issue18780) */
14102 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014103 break;
14104 case 'o':
14105 numnondigits = 2;
14106 result = PyNumber_ToBase(val, 8);
14107 break;
14108 case 'x':
14109 case 'X':
14110 numnondigits = 2;
14111 result = PyNumber_ToBase(val, 16);
14112 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014113 }
14114 if (!result)
14115 return NULL;
14116
14117 assert(unicode_modifiable(result));
14118 assert(PyUnicode_IS_READY(result));
14119 assert(PyUnicode_IS_ASCII(result));
14120
14121 /* To modify the string in-place, there can only be one reference. */
14122 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014123 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014124 PyErr_BadInternalCall();
14125 return NULL;
14126 }
14127 buf = PyUnicode_DATA(result);
14128 llen = PyUnicode_GET_LENGTH(result);
14129 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014130 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014131 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014132 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014133 return NULL;
14134 }
14135 len = (int)llen;
14136 sign = buf[0] == '-';
14137 numnondigits += sign;
14138 numdigits = len - numnondigits;
14139 assert(numdigits > 0);
14140
14141 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014142 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014143 (type == 'o' || type == 'x' || type == 'X'))) {
14144 assert(buf[sign] == '0');
14145 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14146 buf[sign+1] == 'o');
14147 numnondigits -= 2;
14148 buf += 2;
14149 len -= 2;
14150 if (sign)
14151 buf[0] = '-';
14152 assert(len == numnondigits + numdigits);
14153 assert(numdigits > 0);
14154 }
14155
14156 /* Fill with leading zeroes to meet minimum width. */
14157 if (prec > numdigits) {
14158 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14159 numnondigits + prec);
14160 char *b1;
14161 if (!r1) {
14162 Py_DECREF(result);
14163 return NULL;
14164 }
14165 b1 = PyBytes_AS_STRING(r1);
14166 for (i = 0; i < numnondigits; ++i)
14167 *b1++ = *buf++;
14168 for (i = 0; i < prec - numdigits; i++)
14169 *b1++ = '0';
14170 for (i = 0; i < numdigits; i++)
14171 *b1++ = *buf++;
14172 *b1 = '\0';
14173 Py_DECREF(result);
14174 result = r1;
14175 buf = PyBytes_AS_STRING(result);
14176 len = numnondigits + prec;
14177 }
14178
14179 /* Fix up case for hex conversions. */
14180 if (type == 'X') {
14181 /* Need to convert all lower case letters to upper case.
14182 and need to convert 0x to 0X (and -0x to -0X). */
14183 for (i = 0; i < len; i++)
14184 if (buf[i] >= 'a' && buf[i] <= 'x')
14185 buf[i] -= 'a'-'A';
14186 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014187 if (!PyUnicode_Check(result)
14188 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014189 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014190 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014191 Py_DECREF(result);
14192 result = unicode;
14193 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014194 else if (len != PyUnicode_GET_LENGTH(result)) {
14195 if (PyUnicode_Resize(&result, len) < 0)
14196 Py_CLEAR(result);
14197 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014198 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014199}
14200
Ethan Furmandf3ed242014-01-05 06:50:30 -080014201/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014202 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014203 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014204 * -1 and raise an exception on error */
14205static int
Victor Stinnera47082312012-10-04 02:19:54 +020014206mainformatlong(PyObject *v,
14207 struct unicode_format_arg_t *arg,
14208 PyObject **p_output,
14209 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014210{
14211 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014212 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014213
14214 if (!PyNumber_Check(v))
14215 goto wrongtype;
14216
Ethan Furman9ab74802014-03-21 06:38:46 -070014217 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014218 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014219 if (type == 'o' || type == 'x' || type == 'X') {
14220 iobj = PyNumber_Index(v);
14221 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014222 if (PyErr_ExceptionMatches(PyExc_TypeError))
14223 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014224 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014225 }
14226 }
14227 else {
14228 iobj = PyNumber_Long(v);
14229 if (iobj == NULL ) {
14230 if (PyErr_ExceptionMatches(PyExc_TypeError))
14231 goto wrongtype;
14232 return -1;
14233 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014234 }
14235 assert(PyLong_Check(iobj));
14236 }
14237 else {
14238 iobj = v;
14239 Py_INCREF(iobj);
14240 }
14241
14242 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014243 && arg->width == -1 && arg->prec == -1
14244 && !(arg->flags & (F_SIGN | F_BLANK))
14245 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014246 {
14247 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014248 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014249 int base;
14250
Victor Stinnera47082312012-10-04 02:19:54 +020014251 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014252 {
14253 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014254 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014255 case 'd':
14256 case 'i':
14257 case 'u':
14258 base = 10;
14259 break;
14260 case 'o':
14261 base = 8;
14262 break;
14263 case 'x':
14264 case 'X':
14265 base = 16;
14266 break;
14267 }
14268
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014269 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14270 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014271 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014272 }
14273 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014274 return 1;
14275 }
14276
Ethan Furmanb95b5612015-01-23 20:05:18 -080014277 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014278 Py_DECREF(iobj);
14279 if (res == NULL)
14280 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014281 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014282 return 0;
14283
14284wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014285 switch(type)
14286 {
14287 case 'o':
14288 case 'x':
14289 case 'X':
14290 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014291 "%%%c format: an integer is required, "
14292 "not %.200s",
14293 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014294 break;
14295 default:
14296 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014297 "%%%c format: a number is required, "
14298 "not %.200s",
14299 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014300 break;
14301 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014302 return -1;
14303}
14304
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014305static Py_UCS4
14306formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014307{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014308 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014309 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014310 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014311 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014312 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014313 goto onError;
14314 }
14315 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014316 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014317 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014318 /* make sure number is a type of integer */
14319 if (!PyLong_Check(v)) {
14320 iobj = PyNumber_Index(v);
14321 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014322 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014323 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014324 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014325 Py_DECREF(iobj);
14326 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014327 else {
14328 x = PyLong_AsLong(v);
14329 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014330 if (x == -1 && PyErr_Occurred())
14331 goto onError;
14332
Victor Stinner8faf8212011-12-08 22:14:11 +010014333 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014334 PyErr_SetString(PyExc_OverflowError,
14335 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014336 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014337 }
14338
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014339 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014340 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014341
Benjamin Peterson29060642009-01-31 22:14:21 +000014342 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014343 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014344 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014345 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014346}
14347
Victor Stinnera47082312012-10-04 02:19:54 +020014348/* Parse options of an argument: flags, width, precision.
14349 Handle also "%(name)" syntax.
14350
14351 Return 0 if the argument has been formatted into arg->str.
14352 Return 1 if the argument has been written into ctx->writer,
14353 Raise an exception and return -1 on error. */
14354static int
14355unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14356 struct unicode_format_arg_t *arg)
14357{
14358#define FORMAT_READ(ctx) \
14359 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14360
14361 PyObject *v;
14362
Victor Stinnera47082312012-10-04 02:19:54 +020014363 if (arg->ch == '(') {
14364 /* Get argument value from a dictionary. Example: "%(name)s". */
14365 Py_ssize_t keystart;
14366 Py_ssize_t keylen;
14367 PyObject *key;
14368 int pcount = 1;
14369
14370 if (ctx->dict == NULL) {
14371 PyErr_SetString(PyExc_TypeError,
14372 "format requires a mapping");
14373 return -1;
14374 }
14375 ++ctx->fmtpos;
14376 --ctx->fmtcnt;
14377 keystart = ctx->fmtpos;
14378 /* Skip over balanced parentheses */
14379 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14380 arg->ch = FORMAT_READ(ctx);
14381 if (arg->ch == ')')
14382 --pcount;
14383 else if (arg->ch == '(')
14384 ++pcount;
14385 ctx->fmtpos++;
14386 }
14387 keylen = ctx->fmtpos - keystart - 1;
14388 if (ctx->fmtcnt < 0 || pcount > 0) {
14389 PyErr_SetString(PyExc_ValueError,
14390 "incomplete format key");
14391 return -1;
14392 }
14393 key = PyUnicode_Substring(ctx->fmtstr,
14394 keystart, keystart + keylen);
14395 if (key == NULL)
14396 return -1;
14397 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014398 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014399 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014400 }
14401 ctx->args = PyObject_GetItem(ctx->dict, key);
14402 Py_DECREF(key);
14403 if (ctx->args == NULL)
14404 return -1;
14405 ctx->args_owned = 1;
14406 ctx->arglen = -1;
14407 ctx->argidx = -2;
14408 }
14409
14410 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014411 while (--ctx->fmtcnt >= 0) {
14412 arg->ch = FORMAT_READ(ctx);
14413 ctx->fmtpos++;
14414 switch (arg->ch) {
14415 case '-': arg->flags |= F_LJUST; continue;
14416 case '+': arg->flags |= F_SIGN; continue;
14417 case ' ': arg->flags |= F_BLANK; continue;
14418 case '#': arg->flags |= F_ALT; continue;
14419 case '0': arg->flags |= F_ZERO; continue;
14420 }
14421 break;
14422 }
14423
14424 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014425 if (arg->ch == '*') {
14426 v = unicode_format_getnextarg(ctx);
14427 if (v == NULL)
14428 return -1;
14429 if (!PyLong_Check(v)) {
14430 PyErr_SetString(PyExc_TypeError,
14431 "* wants int");
14432 return -1;
14433 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014434 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014435 if (arg->width == -1 && PyErr_Occurred())
14436 return -1;
14437 if (arg->width < 0) {
14438 arg->flags |= F_LJUST;
14439 arg->width = -arg->width;
14440 }
14441 if (--ctx->fmtcnt >= 0) {
14442 arg->ch = FORMAT_READ(ctx);
14443 ctx->fmtpos++;
14444 }
14445 }
14446 else if (arg->ch >= '0' && arg->ch <= '9') {
14447 arg->width = arg->ch - '0';
14448 while (--ctx->fmtcnt >= 0) {
14449 arg->ch = FORMAT_READ(ctx);
14450 ctx->fmtpos++;
14451 if (arg->ch < '0' || arg->ch > '9')
14452 break;
14453 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14454 mixing signed and unsigned comparison. Since arg->ch is between
14455 '0' and '9', casting to int is safe. */
14456 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14457 PyErr_SetString(PyExc_ValueError,
14458 "width too big");
14459 return -1;
14460 }
14461 arg->width = arg->width*10 + (arg->ch - '0');
14462 }
14463 }
14464
14465 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014466 if (arg->ch == '.') {
14467 arg->prec = 0;
14468 if (--ctx->fmtcnt >= 0) {
14469 arg->ch = FORMAT_READ(ctx);
14470 ctx->fmtpos++;
14471 }
14472 if (arg->ch == '*') {
14473 v = unicode_format_getnextarg(ctx);
14474 if (v == NULL)
14475 return -1;
14476 if (!PyLong_Check(v)) {
14477 PyErr_SetString(PyExc_TypeError,
14478 "* wants int");
14479 return -1;
14480 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014481 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014482 if (arg->prec == -1 && PyErr_Occurred())
14483 return -1;
14484 if (arg->prec < 0)
14485 arg->prec = 0;
14486 if (--ctx->fmtcnt >= 0) {
14487 arg->ch = FORMAT_READ(ctx);
14488 ctx->fmtpos++;
14489 }
14490 }
14491 else if (arg->ch >= '0' && arg->ch <= '9') {
14492 arg->prec = arg->ch - '0';
14493 while (--ctx->fmtcnt >= 0) {
14494 arg->ch = FORMAT_READ(ctx);
14495 ctx->fmtpos++;
14496 if (arg->ch < '0' || arg->ch > '9')
14497 break;
14498 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14499 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014500 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014501 return -1;
14502 }
14503 arg->prec = arg->prec*10 + (arg->ch - '0');
14504 }
14505 }
14506 }
14507
14508 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14509 if (ctx->fmtcnt >= 0) {
14510 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14511 if (--ctx->fmtcnt >= 0) {
14512 arg->ch = FORMAT_READ(ctx);
14513 ctx->fmtpos++;
14514 }
14515 }
14516 }
14517 if (ctx->fmtcnt < 0) {
14518 PyErr_SetString(PyExc_ValueError,
14519 "incomplete format");
14520 return -1;
14521 }
14522 return 0;
14523
14524#undef FORMAT_READ
14525}
14526
14527/* Format one argument. Supported conversion specifiers:
14528
14529 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014530 - "i", "d", "u": int or float
14531 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014532 - "e", "E", "f", "F", "g", "G": float
14533 - "c": int or str (1 character)
14534
Victor Stinner8dbd4212012-12-04 09:30:24 +010014535 When possible, the output is written directly into the Unicode writer
14536 (ctx->writer). A string is created when padding is required.
14537
Victor Stinnera47082312012-10-04 02:19:54 +020014538 Return 0 if the argument has been formatted into *p_str,
14539 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014540 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014541static int
14542unicode_format_arg_format(struct unicode_formatter_t *ctx,
14543 struct unicode_format_arg_t *arg,
14544 PyObject **p_str)
14545{
14546 PyObject *v;
14547 _PyUnicodeWriter *writer = &ctx->writer;
14548
14549 if (ctx->fmtcnt == 0)
14550 ctx->writer.overallocate = 0;
14551
Victor Stinnera47082312012-10-04 02:19:54 +020014552 v = unicode_format_getnextarg(ctx);
14553 if (v == NULL)
14554 return -1;
14555
Victor Stinnera47082312012-10-04 02:19:54 +020014556
14557 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014558 case 's':
14559 case 'r':
14560 case 'a':
14561 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14562 /* Fast path */
14563 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14564 return -1;
14565 return 1;
14566 }
14567
14568 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14569 *p_str = v;
14570 Py_INCREF(*p_str);
14571 }
14572 else {
14573 if (arg->ch == 's')
14574 *p_str = PyObject_Str(v);
14575 else if (arg->ch == 'r')
14576 *p_str = PyObject_Repr(v);
14577 else
14578 *p_str = PyObject_ASCII(v);
14579 }
14580 break;
14581
14582 case 'i':
14583 case 'd':
14584 case 'u':
14585 case 'o':
14586 case 'x':
14587 case 'X':
14588 {
14589 int ret = mainformatlong(v, arg, p_str, writer);
14590 if (ret != 0)
14591 return ret;
14592 arg->sign = 1;
14593 break;
14594 }
14595
14596 case 'e':
14597 case 'E':
14598 case 'f':
14599 case 'F':
14600 case 'g':
14601 case 'G':
14602 if (arg->width == -1 && arg->prec == -1
14603 && !(arg->flags & (F_SIGN | F_BLANK)))
14604 {
14605 /* Fast path */
14606 if (formatfloat(v, arg, NULL, writer) == -1)
14607 return -1;
14608 return 1;
14609 }
14610
14611 arg->sign = 1;
14612 if (formatfloat(v, arg, p_str, NULL) == -1)
14613 return -1;
14614 break;
14615
14616 case 'c':
14617 {
14618 Py_UCS4 ch = formatchar(v);
14619 if (ch == (Py_UCS4) -1)
14620 return -1;
14621 if (arg->width == -1 && arg->prec == -1) {
14622 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014623 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014624 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014625 return 1;
14626 }
14627 *p_str = PyUnicode_FromOrdinal(ch);
14628 break;
14629 }
14630
14631 default:
14632 PyErr_Format(PyExc_ValueError,
14633 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014634 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014635 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14636 (int)arg->ch,
14637 ctx->fmtpos - 1);
14638 return -1;
14639 }
14640 if (*p_str == NULL)
14641 return -1;
14642 assert (PyUnicode_Check(*p_str));
14643 return 0;
14644}
14645
14646static int
14647unicode_format_arg_output(struct unicode_formatter_t *ctx,
14648 struct unicode_format_arg_t *arg,
14649 PyObject *str)
14650{
14651 Py_ssize_t len;
14652 enum PyUnicode_Kind kind;
14653 void *pbuf;
14654 Py_ssize_t pindex;
14655 Py_UCS4 signchar;
14656 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014657 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014658 Py_ssize_t sublen;
14659 _PyUnicodeWriter *writer = &ctx->writer;
14660 Py_UCS4 fill;
14661
14662 fill = ' ';
14663 if (arg->sign && arg->flags & F_ZERO)
14664 fill = '0';
14665
14666 if (PyUnicode_READY(str) == -1)
14667 return -1;
14668
14669 len = PyUnicode_GET_LENGTH(str);
14670 if ((arg->width == -1 || arg->width <= len)
14671 && (arg->prec == -1 || arg->prec >= len)
14672 && !(arg->flags & (F_SIGN | F_BLANK)))
14673 {
14674 /* Fast path */
14675 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14676 return -1;
14677 return 0;
14678 }
14679
14680 /* Truncate the string for "s", "r" and "a" formats
14681 if the precision is set */
14682 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14683 if (arg->prec >= 0 && len > arg->prec)
14684 len = arg->prec;
14685 }
14686
14687 /* Adjust sign and width */
14688 kind = PyUnicode_KIND(str);
14689 pbuf = PyUnicode_DATA(str);
14690 pindex = 0;
14691 signchar = '\0';
14692 if (arg->sign) {
14693 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14694 if (ch == '-' || ch == '+') {
14695 signchar = ch;
14696 len--;
14697 pindex++;
14698 }
14699 else if (arg->flags & F_SIGN)
14700 signchar = '+';
14701 else if (arg->flags & F_BLANK)
14702 signchar = ' ';
14703 else
14704 arg->sign = 0;
14705 }
14706 if (arg->width < len)
14707 arg->width = len;
14708
14709 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014710 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014711 if (!(arg->flags & F_LJUST)) {
14712 if (arg->sign) {
14713 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014714 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014715 }
14716 else {
14717 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014718 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014719 }
14720 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014721 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14722 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014723 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014724 }
14725
Victor Stinnera47082312012-10-04 02:19:54 +020014726 buflen = arg->width;
14727 if (arg->sign && len == arg->width)
14728 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014729 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014730 return -1;
14731
14732 /* Write the sign if needed */
14733 if (arg->sign) {
14734 if (fill != ' ') {
14735 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14736 writer->pos += 1;
14737 }
14738 if (arg->width > len)
14739 arg->width--;
14740 }
14741
14742 /* Write the numeric prefix for "x", "X" and "o" formats
14743 if the alternate form is used.
14744 For example, write "0x" for the "%#x" format. */
14745 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14746 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14747 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14748 if (fill != ' ') {
14749 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14750 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14751 writer->pos += 2;
14752 pindex += 2;
14753 }
14754 arg->width -= 2;
14755 if (arg->width < 0)
14756 arg->width = 0;
14757 len -= 2;
14758 }
14759
14760 /* Pad left with the fill character if needed */
14761 if (arg->width > len && !(arg->flags & F_LJUST)) {
14762 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014763 unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014764 writer->pos += sublen;
14765 arg->width = len;
14766 }
14767
14768 /* If padding with spaces: write sign if needed and/or numeric prefix if
14769 the alternate form is used */
14770 if (fill == ' ') {
14771 if (arg->sign) {
14772 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14773 writer->pos += 1;
14774 }
14775 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14776 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14777 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14778 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14779 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14780 writer->pos += 2;
14781 pindex += 2;
14782 }
14783 }
14784
14785 /* Write characters */
14786 if (len) {
14787 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14788 str, pindex, len);
14789 writer->pos += len;
14790 }
14791
14792 /* Pad right with the fill character if needed */
14793 if (arg->width > len) {
14794 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014795 unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014796 writer->pos += sublen;
14797 }
14798 return 0;
14799}
14800
14801/* Helper of PyUnicode_Format(): format one arg.
14802 Return 0 on success, raise an exception and return -1 on error. */
14803static int
14804unicode_format_arg(struct unicode_formatter_t *ctx)
14805{
14806 struct unicode_format_arg_t arg;
14807 PyObject *str;
14808 int ret;
14809
Victor Stinner8dbd4212012-12-04 09:30:24 +010014810 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014811 if (arg.ch == '%') {
14812 ctx->fmtpos++;
14813 ctx->fmtcnt--;
14814 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14815 return -1;
14816 return 0;
14817 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014818 arg.flags = 0;
14819 arg.width = -1;
14820 arg.prec = -1;
14821 arg.sign = 0;
14822 str = NULL;
14823
Victor Stinnera47082312012-10-04 02:19:54 +020014824 ret = unicode_format_arg_parse(ctx, &arg);
14825 if (ret == -1)
14826 return -1;
14827
14828 ret = unicode_format_arg_format(ctx, &arg, &str);
14829 if (ret == -1)
14830 return -1;
14831
14832 if (ret != 1) {
14833 ret = unicode_format_arg_output(ctx, &arg, str);
14834 Py_DECREF(str);
14835 if (ret == -1)
14836 return -1;
14837 }
14838
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014839 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014840 PyErr_SetString(PyExc_TypeError,
14841 "not all arguments converted during string formatting");
14842 return -1;
14843 }
14844 return 0;
14845}
14846
Alexander Belopolsky40018472011-02-26 01:02:56 +000014847PyObject *
14848PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014849{
Victor Stinnera47082312012-10-04 02:19:54 +020014850 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014851
Guido van Rossumd57fd912000-03-10 22:53:23 +000014852 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014853 PyErr_BadInternalCall();
14854 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014855 }
Victor Stinnera47082312012-10-04 02:19:54 +020014856
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014857 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014858 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014859
14860 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014861 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14862 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14863 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14864 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014865
Victor Stinner8f674cc2013-04-17 23:02:17 +020014866 _PyUnicodeWriter_Init(&ctx.writer);
14867 ctx.writer.min_length = ctx.fmtcnt + 100;
14868 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014869
Guido van Rossumd57fd912000-03-10 22:53:23 +000014870 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014871 ctx.arglen = PyTuple_Size(args);
14872 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014873 }
14874 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014875 ctx.arglen = -1;
14876 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014877 }
Victor Stinnera47082312012-10-04 02:19:54 +020014878 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014879 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014880 ctx.dict = args;
14881 else
14882 ctx.dict = NULL;
14883 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014884
Victor Stinnera47082312012-10-04 02:19:54 +020014885 while (--ctx.fmtcnt >= 0) {
14886 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014887 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014888
14889 nonfmtpos = ctx.fmtpos++;
14890 while (ctx.fmtcnt >= 0 &&
14891 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14892 ctx.fmtpos++;
14893 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014894 }
Victor Stinnera47082312012-10-04 02:19:54 +020014895 if (ctx.fmtcnt < 0) {
14896 ctx.fmtpos--;
14897 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014898 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014899
Victor Stinnercfc4c132013-04-03 01:48:39 +020014900 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14901 nonfmtpos, ctx.fmtpos) < 0)
14902 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014903 }
14904 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014905 ctx.fmtpos++;
14906 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014907 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014908 }
14909 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014910
Victor Stinnera47082312012-10-04 02:19:54 +020014911 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014912 PyErr_SetString(PyExc_TypeError,
14913 "not all arguments converted during string formatting");
14914 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014915 }
14916
Victor Stinnera47082312012-10-04 02:19:54 +020014917 if (ctx.args_owned) {
14918 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014919 }
Victor Stinnera47082312012-10-04 02:19:54 +020014920 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014921
Benjamin Peterson29060642009-01-31 22:14:21 +000014922 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014923 _PyUnicodeWriter_Dealloc(&ctx.writer);
14924 if (ctx.args_owned) {
14925 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014926 }
14927 return NULL;
14928}
14929
Jeremy Hylton938ace62002-07-17 16:30:39 +000014930static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014931unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14932
Tim Peters6d6c1a32001-08-02 04:15:00 +000014933static PyObject *
14934unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14935{
Benjamin Peterson29060642009-01-31 22:14:21 +000014936 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014937 static char *kwlist[] = {"object", "encoding", "errors", 0};
14938 char *encoding = NULL;
14939 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014940
Benjamin Peterson14339b62009-01-31 16:36:08 +000014941 if (type != &PyUnicode_Type)
14942 return unicode_subtype_new(type, args, kwds);
14943 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014944 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014945 return NULL;
14946 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014947 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014948 if (encoding == NULL && errors == NULL)
14949 return PyObject_Str(x);
14950 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014951 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014952}
14953
Guido van Rossume023fe02001-08-30 03:12:59 +000014954static PyObject *
14955unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14956{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014957 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014958 Py_ssize_t length, char_size;
14959 int share_wstr, share_utf8;
14960 unsigned int kind;
14961 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014962
Benjamin Peterson14339b62009-01-31 16:36:08 +000014963 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014964
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014965 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014966 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014967 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014968 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014969 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014970 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014971 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014972 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014973
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014974 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014975 if (self == NULL) {
14976 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014977 return NULL;
14978 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014979 kind = PyUnicode_KIND(unicode);
14980 length = PyUnicode_GET_LENGTH(unicode);
14981
14982 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014983#ifdef Py_DEBUG
14984 _PyUnicode_HASH(self) = -1;
14985#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014986 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014987#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014988 _PyUnicode_STATE(self).interned = 0;
14989 _PyUnicode_STATE(self).kind = kind;
14990 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020014991 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014992 _PyUnicode_STATE(self).ready = 1;
14993 _PyUnicode_WSTR(self) = NULL;
14994 _PyUnicode_UTF8_LENGTH(self) = 0;
14995 _PyUnicode_UTF8(self) = NULL;
14996 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020014997 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014998
14999 share_utf8 = 0;
15000 share_wstr = 0;
15001 if (kind == PyUnicode_1BYTE_KIND) {
15002 char_size = 1;
15003 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15004 share_utf8 = 1;
15005 }
15006 else if (kind == PyUnicode_2BYTE_KIND) {
15007 char_size = 2;
15008 if (sizeof(wchar_t) == 2)
15009 share_wstr = 1;
15010 }
15011 else {
15012 assert(kind == PyUnicode_4BYTE_KIND);
15013 char_size = 4;
15014 if (sizeof(wchar_t) == 4)
15015 share_wstr = 1;
15016 }
15017
15018 /* Ensure we won't overflow the length. */
15019 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15020 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015021 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015022 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015023 data = PyObject_MALLOC((length + 1) * char_size);
15024 if (data == NULL) {
15025 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015026 goto onError;
15027 }
15028
Victor Stinnerc3c74152011-10-02 20:39:55 +020015029 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015030 if (share_utf8) {
15031 _PyUnicode_UTF8_LENGTH(self) = length;
15032 _PyUnicode_UTF8(self) = data;
15033 }
15034 if (share_wstr) {
15035 _PyUnicode_WSTR_LENGTH(self) = length;
15036 _PyUnicode_WSTR(self) = (wchar_t *)data;
15037 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015038
Christian Heimesf051e432016-09-13 20:22:02 +020015039 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015040 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015041 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015042#ifdef Py_DEBUG
15043 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15044#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015045 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015046 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015047
15048onError:
15049 Py_DECREF(unicode);
15050 Py_DECREF(self);
15051 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015052}
15053
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015054PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015055"str(object='') -> str\n\
15056str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015057\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015058Create a new string object from the given object. If encoding or\n\
15059errors is specified, then the object must expose a data buffer\n\
15060that will be decoded using the given encoding and error handler.\n\
15061Otherwise, returns the result of object.__str__() (if defined)\n\
15062or repr(object).\n\
15063encoding defaults to sys.getdefaultencoding().\n\
15064errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015065
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015066static PyObject *unicode_iter(PyObject *seq);
15067
Guido van Rossumd57fd912000-03-10 22:53:23 +000015068PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015069 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015070 "str", /* tp_name */
15071 sizeof(PyUnicodeObject), /* tp_basicsize */
15072 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015073 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015074 (destructor)unicode_dealloc, /* tp_dealloc */
15075 0, /* tp_print */
15076 0, /* tp_getattr */
15077 0, /* tp_setattr */
15078 0, /* tp_reserved */
15079 unicode_repr, /* tp_repr */
15080 &unicode_as_number, /* tp_as_number */
15081 &unicode_as_sequence, /* tp_as_sequence */
15082 &unicode_as_mapping, /* tp_as_mapping */
15083 (hashfunc) unicode_hash, /* tp_hash*/
15084 0, /* tp_call*/
15085 (reprfunc) unicode_str, /* tp_str */
15086 PyObject_GenericGetAttr, /* tp_getattro */
15087 0, /* tp_setattro */
15088 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015089 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015090 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15091 unicode_doc, /* tp_doc */
15092 0, /* tp_traverse */
15093 0, /* tp_clear */
15094 PyUnicode_RichCompare, /* tp_richcompare */
15095 0, /* tp_weaklistoffset */
15096 unicode_iter, /* tp_iter */
15097 0, /* tp_iternext */
15098 unicode_methods, /* tp_methods */
15099 0, /* tp_members */
15100 0, /* tp_getset */
15101 &PyBaseObject_Type, /* tp_base */
15102 0, /* tp_dict */
15103 0, /* tp_descr_get */
15104 0, /* tp_descr_set */
15105 0, /* tp_dictoffset */
15106 0, /* tp_init */
15107 0, /* tp_alloc */
15108 unicode_new, /* tp_new */
15109 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015110};
15111
15112/* Initialize the Unicode implementation */
15113
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015114_PyInitError
15115_PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015116{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015117 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015118 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015119 0x000A, /* LINE FEED */
15120 0x000D, /* CARRIAGE RETURN */
15121 0x001C, /* FILE SEPARATOR */
15122 0x001D, /* GROUP SEPARATOR */
15123 0x001E, /* RECORD SEPARATOR */
15124 0x0085, /* NEXT LINE */
15125 0x2028, /* LINE SEPARATOR */
15126 0x2029, /* PARAGRAPH SEPARATOR */
15127 };
15128
Fred Drakee4315f52000-05-09 19:53:39 +000015129 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015130 _Py_INCREF_UNICODE_EMPTY();
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015131 if (!unicode_empty) {
15132 return _Py_INIT_ERR("Can't create empty string");
15133 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020015134 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015135
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015136 if (PyType_Ready(&PyUnicode_Type) < 0) {
15137 return _Py_INIT_ERR("Can't initialize unicode type");
15138 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015139
15140 /* initialize the linebreak bloom filter */
15141 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015142 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015143 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015144
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015145 if (PyType_Ready(&EncodingMapType) < 0) {
15146 return _Py_INIT_ERR("Can't initialize encoding map type");
15147 }
15148 if (PyType_Ready(&PyFieldNameIter_Type) < 0) {
15149 return _Py_INIT_ERR("Can't initialize field name iterator type");
15150 }
15151 if (PyType_Ready(&PyFormatterIter_Type) < 0) {
15152 return _Py_INIT_ERR("Can't initialize formatter iter type");
15153 }
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015154 return _Py_INIT_OK();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015155}
15156
15157/* Finalize the Unicode implementation */
15158
Christian Heimesa156e092008-02-16 07:38:31 +000015159int
15160PyUnicode_ClearFreeList(void)
15161{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015162 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015163}
15164
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015165
Walter Dörwald16807132007-05-25 13:52:07 +000015166void
15167PyUnicode_InternInPlace(PyObject **p)
15168{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015169 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015170 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015171#ifdef Py_DEBUG
15172 assert(s != NULL);
15173 assert(_PyUnicode_CHECK(s));
15174#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015175 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015176 return;
15177#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015178 /* If it's a subclass, we don't really know what putting
15179 it in the interned dict might do. */
15180 if (!PyUnicode_CheckExact(s))
15181 return;
15182 if (PyUnicode_CHECK_INTERNED(s))
15183 return;
15184 if (interned == NULL) {
15185 interned = PyDict_New();
15186 if (interned == NULL) {
15187 PyErr_Clear(); /* Don't leave an exception */
15188 return;
15189 }
15190 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015191 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015192 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015193 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015194 if (t == NULL) {
15195 PyErr_Clear();
15196 return;
15197 }
15198 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015199 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015200 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015201 return;
15202 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015203 /* The two references in interned are not counted by refcnt.
15204 The deallocator will take care of this */
15205 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015206 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015207}
15208
15209void
15210PyUnicode_InternImmortal(PyObject **p)
15211{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015212 PyUnicode_InternInPlace(p);
15213 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015214 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015215 Py_INCREF(*p);
15216 }
Walter Dörwald16807132007-05-25 13:52:07 +000015217}
15218
15219PyObject *
15220PyUnicode_InternFromString(const char *cp)
15221{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015222 PyObject *s = PyUnicode_FromString(cp);
15223 if (s == NULL)
15224 return NULL;
15225 PyUnicode_InternInPlace(&s);
15226 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015227}
15228
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015229
15230#if defined(WITH_VALGRIND) || defined(__INSURE__)
15231static void
15232unicode_release_interned(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015233{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015234 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015235 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015236 Py_ssize_t i, n;
15237 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015238
Benjamin Peterson14339b62009-01-31 16:36:08 +000015239 if (interned == NULL || !PyDict_Check(interned))
15240 return;
15241 keys = PyDict_Keys(interned);
15242 if (keys == NULL || !PyList_Check(keys)) {
15243 PyErr_Clear();
15244 return;
15245 }
Walter Dörwald16807132007-05-25 13:52:07 +000015246
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015247 /* Since unicode_release_interned() is intended to help a leak
Benjamin Peterson14339b62009-01-31 16:36:08 +000015248 detector, interned unicode strings are not forcibly deallocated;
15249 rather, we give them their stolen references back, and then clear
15250 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015251
Benjamin Peterson14339b62009-01-31 16:36:08 +000015252 n = PyList_GET_SIZE(keys);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015253#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015254 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015255 n);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015256#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015257 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015258 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015259 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015260 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015261 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015262 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015263 case SSTATE_NOT_INTERNED:
15264 /* XXX Shouldn't happen */
15265 break;
15266 case SSTATE_INTERNED_IMMORTAL:
15267 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015268 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015269 break;
15270 case SSTATE_INTERNED_MORTAL:
15271 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015272 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015273 break;
15274 default:
15275 Py_FatalError("Inconsistent interned string state.");
15276 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015277 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015278 }
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015279#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015280 fprintf(stderr, "total size of all interned strings: "
15281 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15282 "mortal/immortal\n", mortal_size, immortal_size);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015283#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015284 Py_DECREF(keys);
15285 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015286 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015287}
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015288#endif
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015289
15290
15291/********************* Unicode Iterator **************************/
15292
15293typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015294 PyObject_HEAD
15295 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015296 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015297} unicodeiterobject;
15298
15299static void
15300unicodeiter_dealloc(unicodeiterobject *it)
15301{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015302 _PyObject_GC_UNTRACK(it);
15303 Py_XDECREF(it->it_seq);
15304 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015305}
15306
15307static int
15308unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15309{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015310 Py_VISIT(it->it_seq);
15311 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015312}
15313
15314static PyObject *
15315unicodeiter_next(unicodeiterobject *it)
15316{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015317 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015318
Benjamin Peterson14339b62009-01-31 16:36:08 +000015319 assert(it != NULL);
15320 seq = it->it_seq;
15321 if (seq == NULL)
15322 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015323 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015324
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015325 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15326 int kind = PyUnicode_KIND(seq);
15327 void *data = PyUnicode_DATA(seq);
15328 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15329 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015330 if (item != NULL)
15331 ++it->it_index;
15332 return item;
15333 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015334
Benjamin Peterson14339b62009-01-31 16:36:08 +000015335 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015336 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015337 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015338}
15339
15340static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015341unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015342{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015343 Py_ssize_t len = 0;
15344 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015345 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015346 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015347}
15348
15349PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15350
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015351static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015352unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015353{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015354 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015355 if (it->it_seq != NULL) {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015356 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015357 it->it_seq, it->it_index);
15358 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015359 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015360 if (u == NULL)
15361 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015362 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015363 }
15364}
15365
15366PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15367
15368static PyObject *
15369unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15370{
15371 Py_ssize_t index = PyLong_AsSsize_t(state);
15372 if (index == -1 && PyErr_Occurred())
15373 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015374 if (it->it_seq != NULL) {
15375 if (index < 0)
15376 index = 0;
15377 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15378 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15379 it->it_index = index;
15380 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015381 Py_RETURN_NONE;
15382}
15383
15384PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15385
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015386static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015387 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015388 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015389 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15390 reduce_doc},
15391 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15392 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015393 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015394};
15395
15396PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015397 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15398 "str_iterator", /* tp_name */
15399 sizeof(unicodeiterobject), /* tp_basicsize */
15400 0, /* tp_itemsize */
15401 /* methods */
15402 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15403 0, /* tp_print */
15404 0, /* tp_getattr */
15405 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015406 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015407 0, /* tp_repr */
15408 0, /* tp_as_number */
15409 0, /* tp_as_sequence */
15410 0, /* tp_as_mapping */
15411 0, /* tp_hash */
15412 0, /* tp_call */
15413 0, /* tp_str */
15414 PyObject_GenericGetAttr, /* tp_getattro */
15415 0, /* tp_setattro */
15416 0, /* tp_as_buffer */
15417 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15418 0, /* tp_doc */
15419 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15420 0, /* tp_clear */
15421 0, /* tp_richcompare */
15422 0, /* tp_weaklistoffset */
15423 PyObject_SelfIter, /* tp_iter */
15424 (iternextfunc)unicodeiter_next, /* tp_iternext */
15425 unicodeiter_methods, /* tp_methods */
15426 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015427};
15428
15429static PyObject *
15430unicode_iter(PyObject *seq)
15431{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015432 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015433
Benjamin Peterson14339b62009-01-31 16:36:08 +000015434 if (!PyUnicode_Check(seq)) {
15435 PyErr_BadInternalCall();
15436 return NULL;
15437 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015438 if (PyUnicode_READY(seq) == -1)
15439 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015440 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15441 if (it == NULL)
15442 return NULL;
15443 it->it_index = 0;
15444 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015445 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015446 _PyObject_GC_TRACK(it);
15447 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015448}
15449
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015450
15451size_t
15452Py_UNICODE_strlen(const Py_UNICODE *u)
15453{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015454 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015455}
15456
15457Py_UNICODE*
15458Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15459{
15460 Py_UNICODE *u = s1;
15461 while ((*u++ = *s2++));
15462 return s1;
15463}
15464
15465Py_UNICODE*
15466Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15467{
15468 Py_UNICODE *u = s1;
15469 while ((*u++ = *s2++))
15470 if (n-- == 0)
15471 break;
15472 return s1;
15473}
15474
15475Py_UNICODE*
15476Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15477{
15478 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015479 u1 += wcslen(u1);
15480 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015481 return s1;
15482}
15483
15484int
15485Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15486{
15487 while (*s1 && *s2 && *s1 == *s2)
15488 s1++, s2++;
15489 if (*s1 && *s2)
15490 return (*s1 < *s2) ? -1 : +1;
15491 if (*s1)
15492 return 1;
15493 if (*s2)
15494 return -1;
15495 return 0;
15496}
15497
15498int
15499Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15500{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015501 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015502 for (; n != 0; n--) {
15503 u1 = *s1;
15504 u2 = *s2;
15505 if (u1 != u2)
15506 return (u1 < u2) ? -1 : +1;
15507 if (u1 == '\0')
15508 return 0;
15509 s1++;
15510 s2++;
15511 }
15512 return 0;
15513}
15514
15515Py_UNICODE*
15516Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15517{
15518 const Py_UNICODE *p;
15519 for (p = s; *p; p++)
15520 if (*p == c)
15521 return (Py_UNICODE*)p;
15522 return NULL;
15523}
15524
15525Py_UNICODE*
15526Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15527{
15528 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015529 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015530 while (p != s) {
15531 p--;
15532 if (*p == c)
15533 return (Py_UNICODE*)p;
15534 }
15535 return NULL;
15536}
Victor Stinner331ea922010-08-10 16:37:20 +000015537
Victor Stinner71133ff2010-09-01 23:43:53 +000015538Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015539PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015540{
Victor Stinner577db2c2011-10-11 22:12:48 +020015541 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015542 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015544 if (!PyUnicode_Check(unicode)) {
15545 PyErr_BadArgument();
15546 return NULL;
15547 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015548 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015549 if (u == NULL)
15550 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015551 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015552 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015553 PyErr_NoMemory();
15554 return NULL;
15555 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015556 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015557 size *= sizeof(Py_UNICODE);
15558 copy = PyMem_Malloc(size);
15559 if (copy == NULL) {
15560 PyErr_NoMemory();
15561 return NULL;
15562 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015563 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015564 return copy;
15565}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015566
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015567
15568void
15569_PyUnicode_Fini(void)
15570{
15571#if defined(WITH_VALGRIND) || defined(__INSURE__)
15572 /* Insure++ is a memory analysis tool that aids in discovering
15573 * memory leaks and other memory problems. On Python exit, the
15574 * interned string dictionaries are flagged as being in use at exit
15575 * (which it is). Under normal circumstances, this is fine because
15576 * the memory will be automatically reclaimed by the system. Under
15577 * memory debugging, it's a huge source of useless noise, so we
15578 * trade off slower shutdown for less distraction in the memory
15579 * reports. -baw
15580 */
15581 unicode_release_interned();
15582#endif /* __INSURE__ */
15583
15584 Py_CLEAR(unicode_empty);
15585
15586 for (Py_ssize_t i = 0; i < 256; i++) {
15587 Py_CLEAR(unicode_latin1[i]);
15588 }
15589 _PyUnicode_ClearStaticStrings();
15590 (void)PyUnicode_ClearFreeList();
15591}
15592
15593
Georg Brandl66c221e2010-10-14 07:04:07 +000015594/* A _string module, to export formatter_parser and formatter_field_name_split
15595 to the string.Formatter class implemented in Python. */
15596
15597static PyMethodDef _string_methods[] = {
15598 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15599 METH_O, PyDoc_STR("split the argument as a field name")},
15600 {"formatter_parser", (PyCFunction) formatter_parser,
15601 METH_O, PyDoc_STR("parse the argument as a format string")},
15602 {NULL, NULL}
15603};
15604
15605static struct PyModuleDef _string_module = {
15606 PyModuleDef_HEAD_INIT,
15607 "_string",
15608 PyDoc_STR("string helper module"),
15609 0,
15610 _string_methods,
15611 NULL,
15612 NULL,
15613 NULL,
15614 NULL
15615};
15616
15617PyMODINIT_FUNC
15618PyInit__string(void)
15619{
15620 return PyModule_Create(&_string_module);
15621}
15622
15623
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015624#ifdef __cplusplus
15625}
15626#endif