blob: c0b345be7e8d3ba75f2627a7b5d3df5e106b82c8 [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:
Serhiy Storchaka7a465cb2019-03-30 08:23:38 +02004886 if (s == end || consumed) {
4887 goto End;
4888 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004889 errmsg = "invalid continuation byte";
4890 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004891 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004892 break;
4893 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004894 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004895 goto onError;
4896 continue;
4897 }
4898
Victor Stinner1d65d912015-10-05 13:43:50 +02004899 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02004900 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner1d65d912015-10-05 13:43:50 +02004901
4902 switch (error_handler) {
4903 case _Py_ERROR_IGNORE:
4904 s += (endinpos - startinpos);
4905 break;
4906
4907 case _Py_ERROR_REPLACE:
4908 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4909 goto onError;
4910 s += (endinpos - startinpos);
4911 break;
4912
4913 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004914 {
4915 Py_ssize_t i;
4916
Victor Stinner1d65d912015-10-05 13:43:50 +02004917 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4918 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004919 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004920 ch = (Py_UCS4)(unsigned char)(starts[i]);
4921 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4922 ch + 0xdc00);
4923 writer.pos++;
4924 }
4925 s += (endinpos - startinpos);
4926 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004927 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004928
4929 default:
4930 if (unicode_decode_call_errorhandler_writer(
4931 errors, &error_handler_obj,
4932 "utf-8", errmsg,
4933 &starts, &end, &startinpos, &endinpos, &exc, &s,
4934 &writer))
4935 goto onError;
4936 }
Victor Stinner785938e2011-12-11 20:09:03 +01004937 }
4938
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004939End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004940 if (consumed)
4941 *consumed = s - starts;
4942
Victor Stinner1d65d912015-10-05 13:43:50 +02004943 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004944 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004945 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004946
4947onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004948 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004949 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004950 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004951 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004952}
4953
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004954
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004955/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4956 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004957
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004958 On success, write a pointer to a newly allocated wide character string into
4959 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4960 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004961
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004962 On memory allocation failure, return -1.
4963
4964 On decoding error (if surrogateescape is zero), return -2. If wlen is
4965 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4966 is not NULL, write the decoding error message into *reason. */
4967int
4968_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
Victor Stinner3d4226a2018-08-29 22:21:32 +02004969 const char **reason, _Py_error_handler errors)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004970{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004971 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004972 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004973 wchar_t *unicode;
4974 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004975
Victor Stinner3d4226a2018-08-29 22:21:32 +02004976 int surrogateescape = 0;
4977 int surrogatepass = 0;
4978 switch (errors)
4979 {
4980 case _Py_ERROR_STRICT:
4981 break;
4982 case _Py_ERROR_SURROGATEESCAPE:
4983 surrogateescape = 1;
4984 break;
4985 case _Py_ERROR_SURROGATEPASS:
4986 surrogatepass = 1;
4987 break;
4988 default:
4989 return -3;
4990 }
4991
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004992 /* Note: size will always be longer than the resulting Unicode
4993 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004994 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004995 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004996 }
4997
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004998 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004999 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005000 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01005001 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005002
5003 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005004 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005005 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005006 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005007 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005008#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005009 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005010#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005011 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005012#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005013 if (ch > 0xFF) {
5014#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07005015 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005016#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02005017 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005018 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005019 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
5020 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
5021#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005022 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005023 else {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005024 if (!ch && s == e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005025 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005026 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005027
5028 if (surrogateescape) {
5029 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5030 }
5031 else {
5032 /* Is it a valid three-byte code? */
5033 if (surrogatepass
5034 && (e - s) >= 3
5035 && (s[0] & 0xf0) == 0xe0
5036 && (s[1] & 0xc0) == 0x80
5037 && (s[2] & 0xc0) == 0x80)
5038 {
5039 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5040 s += 3;
5041 unicode[outpos++] = ch;
5042 }
5043 else {
5044 PyMem_RawFree(unicode );
5045 if (reason != NULL) {
5046 switch (ch) {
5047 case 0:
5048 *reason = "unexpected end of data";
5049 break;
5050 case 1:
5051 *reason = "invalid start byte";
5052 break;
5053 /* 2, 3, 4 */
5054 default:
5055 *reason = "invalid continuation byte";
5056 break;
5057 }
5058 }
5059 if (wlen != NULL) {
5060 *wlen = s - orig_s;
5061 }
5062 return -2;
5063 }
5064 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005065 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005066 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005067 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005068 if (wlen) {
5069 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005070 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005071 *wstr = unicode;
5072 return 0;
5073}
5074
Victor Stinner5f9cf232019-03-19 01:46:25 +01005075
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005076wchar_t*
Victor Stinner5f9cf232019-03-19 01:46:25 +01005077_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
5078 size_t *wlen)
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005079{
5080 wchar_t *wstr;
Victor Stinner5f9cf232019-03-19 01:46:25 +01005081 int res = _Py_DecodeUTF8Ex(arg, arglen,
5082 &wstr, wlen,
5083 NULL, _Py_ERROR_SURROGATEESCAPE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005084 if (res != 0) {
Victor Stinner5f9cf232019-03-19 01:46:25 +01005085 /* _Py_DecodeUTF8Ex() must support _Py_ERROR_SURROGATEESCAPE */
5086 assert(res != -3);
5087 if (wlen) {
5088 *wlen = (size_t)res;
5089 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005090 return NULL;
5091 }
5092 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005093}
5094
Antoine Pitrouab868312009-01-10 15:40:25 +00005095
Victor Stinnere47e6982017-12-21 15:45:16 +01005096/* UTF-8 encoder using the surrogateescape error handler .
5097
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005098 On success, return 0 and write the newly allocated character string (use
5099 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005100
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005101 On encoding failure, return -2 and write the position of the invalid
5102 surrogate character into *error_pos (if error_pos is set) and the decoding
5103 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005104
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005105 On memory allocation failure, return -1. */
5106int
5107_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005108 const char **reason, int raw_malloc, _Py_error_handler errors)
Victor Stinnere47e6982017-12-21 15:45:16 +01005109{
5110 const Py_ssize_t max_char_size = 4;
5111 Py_ssize_t len = wcslen(text);
5112
5113 assert(len >= 0);
5114
Victor Stinner3d4226a2018-08-29 22:21:32 +02005115 int surrogateescape = 0;
5116 int surrogatepass = 0;
5117 switch (errors)
5118 {
5119 case _Py_ERROR_STRICT:
5120 break;
5121 case _Py_ERROR_SURROGATEESCAPE:
5122 surrogateescape = 1;
5123 break;
5124 case _Py_ERROR_SURROGATEPASS:
5125 surrogatepass = 1;
5126 break;
5127 default:
5128 return -3;
5129 }
5130
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005131 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5132 return -1;
5133 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005134 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005135 if (raw_malloc) {
5136 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005137 }
5138 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005139 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005140 }
5141 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005142 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005143 }
5144
5145 char *p = bytes;
5146 Py_ssize_t i;
Victor Stinner3d4226a2018-08-29 22:21:32 +02005147 for (i = 0; i < len; ) {
5148 Py_ssize_t ch_pos = i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005149 Py_UCS4 ch = text[i];
Victor Stinner3d4226a2018-08-29 22:21:32 +02005150 i++;
5151#if Py_UNICODE_SIZE == 2
5152 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
5153 && i < len
5154 && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5155 {
5156 ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5157 i++;
5158 }
5159#endif
Victor Stinnere47e6982017-12-21 15:45:16 +01005160
5161 if (ch < 0x80) {
5162 /* Encode ASCII */
5163 *p++ = (char) ch;
5164
5165 }
5166 else if (ch < 0x0800) {
5167 /* Encode Latin-1 */
5168 *p++ = (char)(0xc0 | (ch >> 6));
5169 *p++ = (char)(0x80 | (ch & 0x3f));
5170 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005171 else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005172 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005173 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005174 if (error_pos != NULL) {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005175 *error_pos = (size_t)ch_pos;
Victor Stinnere47e6982017-12-21 15:45:16 +01005176 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005177 if (reason != NULL) {
5178 *reason = "encoding error";
5179 }
5180 if (raw_malloc) {
5181 PyMem_RawFree(bytes);
5182 }
5183 else {
5184 PyMem_Free(bytes);
5185 }
5186 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005187 }
5188 *p++ = (char)(ch & 0xff);
5189 }
5190 else if (ch < 0x10000) {
5191 *p++ = (char)(0xe0 | (ch >> 12));
5192 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5193 *p++ = (char)(0x80 | (ch & 0x3f));
5194 }
5195 else { /* ch >= 0x10000 */
5196 assert(ch <= MAX_UNICODE);
5197 /* Encode UCS4 Unicode ordinals */
5198 *p++ = (char)(0xf0 | (ch >> 18));
5199 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5200 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5201 *p++ = (char)(0x80 | (ch & 0x3f));
5202 }
5203 }
5204 *p++ = '\0';
5205
5206 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005207 char *bytes2;
5208 if (raw_malloc) {
5209 bytes2 = PyMem_RawRealloc(bytes, final_size);
5210 }
5211 else {
5212 bytes2 = PyMem_Realloc(bytes, final_size);
5213 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005214 if (bytes2 == NULL) {
5215 if (error_pos != NULL) {
5216 *error_pos = (size_t)-1;
5217 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005218 if (raw_malloc) {
5219 PyMem_RawFree(bytes);
5220 }
5221 else {
5222 PyMem_Free(bytes);
5223 }
5224 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005225 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005226 *str = bytes2;
5227 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005228}
5229
5230
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005231/* Primary internal function which creates utf8 encoded bytes objects.
5232
5233 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005234 and allocate exactly as much space needed at the end. Else allocate the
5235 maximum possible needed (4 result bytes per Unicode character), and return
5236 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005237*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005238PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005239_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005240{
Victor Stinner6099a032011-12-18 14:22:26 +01005241 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005242 void *data;
5243 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005244
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005245 if (!PyUnicode_Check(unicode)) {
5246 PyErr_BadArgument();
5247 return NULL;
5248 }
5249
5250 if (PyUnicode_READY(unicode) == -1)
5251 return NULL;
5252
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005253 if (PyUnicode_UTF8(unicode))
5254 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5255 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005256
5257 kind = PyUnicode_KIND(unicode);
5258 data = PyUnicode_DATA(unicode);
5259 size = PyUnicode_GET_LENGTH(unicode);
5260
Benjamin Petersonead6b532011-12-20 17:23:42 -06005261 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005262 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005263 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005264 case PyUnicode_1BYTE_KIND:
5265 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5266 assert(!PyUnicode_IS_ASCII(unicode));
5267 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5268 case PyUnicode_2BYTE_KIND:
5269 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5270 case PyUnicode_4BYTE_KIND:
5271 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005272 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005273}
5274
Alexander Belopolsky40018472011-02-26 01:02:56 +00005275PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005276PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5277 Py_ssize_t size,
5278 const char *errors)
5279{
5280 PyObject *v, *unicode;
5281
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005282 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005283 if (unicode == NULL)
5284 return NULL;
5285 v = _PyUnicode_AsUTF8String(unicode, errors);
5286 Py_DECREF(unicode);
5287 return v;
5288}
5289
5290PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005291PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005292{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005293 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005294}
5295
Walter Dörwald41980ca2007-08-16 21:55:45 +00005296/* --- UTF-32 Codec ------------------------------------------------------- */
5297
5298PyObject *
5299PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005300 Py_ssize_t size,
5301 const char *errors,
5302 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005303{
5304 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5305}
5306
5307PyObject *
5308PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005309 Py_ssize_t size,
5310 const char *errors,
5311 int *byteorder,
5312 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005313{
5314 const char *starts = s;
5315 Py_ssize_t startinpos;
5316 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005317 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005318 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005319 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005320 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005321 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005322 PyObject *errorHandler = NULL;
5323 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005324
Walter Dörwald41980ca2007-08-16 21:55:45 +00005325 q = (unsigned char *)s;
5326 e = q + size;
5327
5328 if (byteorder)
5329 bo = *byteorder;
5330
5331 /* Check for BOM marks (U+FEFF) in the input and adjust current
5332 byte order setting accordingly. In native mode, the leading BOM
5333 mark is skipped, in all other modes, it is copied to the output
5334 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005335 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005336 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005337 if (bom == 0x0000FEFF) {
5338 bo = -1;
5339 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005340 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005341 else if (bom == 0xFFFE0000) {
5342 bo = 1;
5343 q += 4;
5344 }
5345 if (byteorder)
5346 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005347 }
5348
Victor Stinnere64322e2012-10-30 23:12:47 +01005349 if (q == e) {
5350 if (consumed)
5351 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005352 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005353 }
5354
Victor Stinnere64322e2012-10-30 23:12:47 +01005355#ifdef WORDS_BIGENDIAN
5356 le = bo < 0;
5357#else
5358 le = bo <= 0;
5359#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005360 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005361
Victor Stinner8f674cc2013-04-17 23:02:17 +02005362 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005363 writer.min_length = (e - q + 3) / 4;
5364 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005365 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005366
Victor Stinnere64322e2012-10-30 23:12:47 +01005367 while (1) {
5368 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005369 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005370
Victor Stinnere64322e2012-10-30 23:12:47 +01005371 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005372 enum PyUnicode_Kind kind = writer.kind;
5373 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005374 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005375 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005376 if (le) {
5377 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005378 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005379 if (ch > maxch)
5380 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005381 if (kind != PyUnicode_1BYTE_KIND &&
5382 Py_UNICODE_IS_SURROGATE(ch))
5383 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005384 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005385 q += 4;
5386 } while (q <= last);
5387 }
5388 else {
5389 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005390 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005391 if (ch > maxch)
5392 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005393 if (kind != PyUnicode_1BYTE_KIND &&
5394 Py_UNICODE_IS_SURROGATE(ch))
5395 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005396 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005397 q += 4;
5398 } while (q <= last);
5399 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005400 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005401 }
5402
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005403 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005404 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005405 startinpos = ((const char *)q) - starts;
5406 endinpos = startinpos + 4;
5407 }
5408 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005409 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005410 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005411 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005412 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005413 startinpos = ((const char *)q) - starts;
5414 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005415 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005416 else {
5417 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005418 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005419 goto onError;
5420 q += 4;
5421 continue;
5422 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005423 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005424 startinpos = ((const char *)q) - starts;
5425 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005426 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005427
5428 /* The remaining input chars are ignored if the callback
5429 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005430 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005431 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005432 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005433 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005434 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005435 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005436 }
5437
Walter Dörwald41980ca2007-08-16 21:55:45 +00005438 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005439 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005440
Walter Dörwald41980ca2007-08-16 21:55:45 +00005441 Py_XDECREF(errorHandler);
5442 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005443 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005444
Benjamin Peterson29060642009-01-31 22:14:21 +00005445 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005446 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005447 Py_XDECREF(errorHandler);
5448 Py_XDECREF(exc);
5449 return NULL;
5450}
5451
5452PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005453_PyUnicode_EncodeUTF32(PyObject *str,
5454 const char *errors,
5455 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005456{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005457 enum PyUnicode_Kind kind;
5458 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005459 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005460 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005461 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005462#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005463 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005464#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005465 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005466#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005467 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005468 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005469 PyObject *errorHandler = NULL;
5470 PyObject *exc = NULL;
5471 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005472
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005473 if (!PyUnicode_Check(str)) {
5474 PyErr_BadArgument();
5475 return NULL;
5476 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005477 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005478 return NULL;
5479 kind = PyUnicode_KIND(str);
5480 data = PyUnicode_DATA(str);
5481 len = PyUnicode_GET_LENGTH(str);
5482
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005483 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005484 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005485 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005486 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005487 if (v == NULL)
5488 return NULL;
5489
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005490 /* output buffer is 4-bytes aligned */
5491 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005492 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005493 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005494 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005495 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005496 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005497
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005498 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005499 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005500 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005501 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005502 else
5503 encoding = "utf-32";
5504
5505 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005506 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5507 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005508 }
5509
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005510 pos = 0;
5511 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005512 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005513
5514 if (kind == PyUnicode_2BYTE_KIND) {
5515 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5516 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005517 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005518 else {
5519 assert(kind == PyUnicode_4BYTE_KIND);
5520 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5521 &out, native_ordering);
5522 }
5523 if (pos == len)
5524 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005525
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005526 rep = unicode_encode_call_errorhandler(
5527 errors, &errorHandler,
5528 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005529 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005530 if (!rep)
5531 goto error;
5532
5533 if (PyBytes_Check(rep)) {
5534 repsize = PyBytes_GET_SIZE(rep);
5535 if (repsize & 3) {
5536 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005537 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005538 "surrogates not allowed");
5539 goto error;
5540 }
5541 moreunits = repsize / 4;
5542 }
5543 else {
5544 assert(PyUnicode_Check(rep));
5545 if (PyUnicode_READY(rep) < 0)
5546 goto error;
5547 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5548 if (!PyUnicode_IS_ASCII(rep)) {
5549 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005550 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005551 "surrogates not allowed");
5552 goto error;
5553 }
5554 }
5555
5556 /* four bytes are reserved for each surrogate */
5557 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005558 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005559 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005560 /* integer overflow */
5561 PyErr_NoMemory();
5562 goto error;
5563 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005564 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005565 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005566 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005567 }
5568
5569 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005570 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005571 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005572 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005573 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005574 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5575 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005576 }
5577
5578 Py_CLEAR(rep);
5579 }
5580
5581 /* Cut back to size actually needed. This is necessary for, for example,
5582 encoding of a string containing isolated surrogates and the 'ignore'
5583 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005584 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005585 if (nsize != PyBytes_GET_SIZE(v))
5586 _PyBytes_Resize(&v, nsize);
5587 Py_XDECREF(errorHandler);
5588 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005589 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005590 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005591 error:
5592 Py_XDECREF(rep);
5593 Py_XDECREF(errorHandler);
5594 Py_XDECREF(exc);
5595 Py_XDECREF(v);
5596 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005597}
5598
Alexander Belopolsky40018472011-02-26 01:02:56 +00005599PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005600PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5601 Py_ssize_t size,
5602 const char *errors,
5603 int byteorder)
5604{
5605 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005606 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005607 if (tmp == NULL)
5608 return NULL;
5609 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5610 Py_DECREF(tmp);
5611 return result;
5612}
5613
5614PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005615PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005616{
Victor Stinnerb960b342011-11-20 19:12:52 +01005617 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005618}
5619
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620/* --- UTF-16 Codec ------------------------------------------------------- */
5621
Tim Peters772747b2001-08-09 22:21:55 +00005622PyObject *
5623PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005624 Py_ssize_t size,
5625 const char *errors,
5626 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005627{
Walter Dörwald69652032004-09-07 20:24:22 +00005628 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5629}
5630
5631PyObject *
5632PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005633 Py_ssize_t size,
5634 const char *errors,
5635 int *byteorder,
5636 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005637{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005638 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005639 Py_ssize_t startinpos;
5640 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005641 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005642 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005643 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005644 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005645 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005646 PyObject *errorHandler = NULL;
5647 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005648 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005649
Tim Peters772747b2001-08-09 22:21:55 +00005650 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005651 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005652
5653 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005654 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005655
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005656 /* Check for BOM marks (U+FEFF) in the input and adjust current
5657 byte order setting accordingly. In native mode, the leading BOM
5658 mark is skipped, in all other modes, it is copied to the output
5659 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005660 if (bo == 0 && size >= 2) {
5661 const Py_UCS4 bom = (q[1] << 8) | q[0];
5662 if (bom == 0xFEFF) {
5663 q += 2;
5664 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005665 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005666 else if (bom == 0xFFFE) {
5667 q += 2;
5668 bo = 1;
5669 }
5670 if (byteorder)
5671 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005672 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673
Antoine Pitrou63065d72012-05-15 23:48:04 +02005674 if (q == e) {
5675 if (consumed)
5676 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005677 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005678 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005679
Christian Heimes743e0cd2012-10-17 23:52:17 +02005680#if PY_LITTLE_ENDIAN
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-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005683#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005684 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005685 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005686#endif
Tim Peters772747b2001-08-09 22:21:55 +00005687
Antoine Pitrou63065d72012-05-15 23:48:04 +02005688 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005689 character count normally. Error handler will take care of
5690 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005691 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005692 writer.min_length = (e - q + 1) / 2;
5693 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005694 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005695
Antoine Pitrou63065d72012-05-15 23:48:04 +02005696 while (1) {
5697 Py_UCS4 ch = 0;
5698 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005699 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005700 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005701 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005702 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005703 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005704 native_ordering);
5705 else
5706 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005707 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005708 native_ordering);
5709 } else if (kind == PyUnicode_2BYTE_KIND) {
5710 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005711 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005712 native_ordering);
5713 } else {
5714 assert(kind == PyUnicode_4BYTE_KIND);
5715 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005716 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005717 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005718 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005719 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005720
Antoine Pitrou63065d72012-05-15 23:48:04 +02005721 switch (ch)
5722 {
5723 case 0:
5724 /* remaining byte at the end? (size should be even) */
5725 if (q == e || consumed)
5726 goto End;
5727 errmsg = "truncated data";
5728 startinpos = ((const char *)q) - starts;
5729 endinpos = ((const char *)e) - starts;
5730 break;
5731 /* The remaining input chars are ignored if the callback
5732 chooses to skip the input */
5733 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005734 q -= 2;
5735 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005736 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005737 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005738 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005739 endinpos = ((const char *)e) - starts;
5740 break;
5741 case 2:
5742 errmsg = "illegal encoding";
5743 startinpos = ((const char *)q) - 2 - starts;
5744 endinpos = startinpos + 2;
5745 break;
5746 case 3:
5747 errmsg = "illegal UTF-16 surrogate";
5748 startinpos = ((const char *)q) - 4 - starts;
5749 endinpos = startinpos + 2;
5750 break;
5751 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005752 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005753 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005754 continue;
5755 }
5756
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005757 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005758 errors,
5759 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005760 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005761 &starts,
5762 (const char **)&e,
5763 &startinpos,
5764 &endinpos,
5765 &exc,
5766 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005767 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005768 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005769 }
5770
Antoine Pitrou63065d72012-05-15 23:48:04 +02005771End:
Walter Dörwald69652032004-09-07 20:24:22 +00005772 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005773 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005774
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005775 Py_XDECREF(errorHandler);
5776 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005777 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005778
Benjamin Peterson29060642009-01-31 22:14:21 +00005779 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005780 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005781 Py_XDECREF(errorHandler);
5782 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005783 return NULL;
5784}
5785
Tim Peters772747b2001-08-09 22:21:55 +00005786PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005787_PyUnicode_EncodeUTF16(PyObject *str,
5788 const char *errors,
5789 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005790{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005791 enum PyUnicode_Kind kind;
5792 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005793 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005794 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005795 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005796 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005797#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005798 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005799#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005800 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005801#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005802 const char *encoding;
5803 Py_ssize_t nsize, pos;
5804 PyObject *errorHandler = NULL;
5805 PyObject *exc = NULL;
5806 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005807
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005808 if (!PyUnicode_Check(str)) {
5809 PyErr_BadArgument();
5810 return NULL;
5811 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005812 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005813 return NULL;
5814 kind = PyUnicode_KIND(str);
5815 data = PyUnicode_DATA(str);
5816 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005817
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005818 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005819 if (kind == PyUnicode_4BYTE_KIND) {
5820 const Py_UCS4 *in = (const Py_UCS4 *)data;
5821 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005822 while (in < end) {
5823 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005824 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005825 }
5826 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005827 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005828 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005829 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005830 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005831 nsize = len + pairs + (byteorder == 0);
5832 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005833 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005834 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005835 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005836
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005837 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005838 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005839 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005840 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005841 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005842 }
5843 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005844 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005845 }
Tim Peters772747b2001-08-09 22:21:55 +00005846
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005847 if (kind == PyUnicode_1BYTE_KIND) {
5848 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5849 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005850 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005851
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005852 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005853 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005854 }
5855 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005856 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005857 }
5858 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005859 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005860 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005861
5862 pos = 0;
5863 while (pos < len) {
5864 Py_ssize_t repsize, moreunits;
5865
5866 if (kind == PyUnicode_2BYTE_KIND) {
5867 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5868 &out, native_ordering);
5869 }
5870 else {
5871 assert(kind == PyUnicode_4BYTE_KIND);
5872 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5873 &out, native_ordering);
5874 }
5875 if (pos == len)
5876 break;
5877
5878 rep = unicode_encode_call_errorhandler(
5879 errors, &errorHandler,
5880 encoding, "surrogates not allowed",
5881 str, &exc, pos, pos + 1, &pos);
5882 if (!rep)
5883 goto error;
5884
5885 if (PyBytes_Check(rep)) {
5886 repsize = PyBytes_GET_SIZE(rep);
5887 if (repsize & 1) {
5888 raise_encode_exception(&exc, encoding,
5889 str, pos - 1, pos,
5890 "surrogates not allowed");
5891 goto error;
5892 }
5893 moreunits = repsize / 2;
5894 }
5895 else {
5896 assert(PyUnicode_Check(rep));
5897 if (PyUnicode_READY(rep) < 0)
5898 goto error;
5899 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5900 if (!PyUnicode_IS_ASCII(rep)) {
5901 raise_encode_exception(&exc, encoding,
5902 str, pos - 1, pos,
5903 "surrogates not allowed");
5904 goto error;
5905 }
5906 }
5907
5908 /* two bytes are reserved for each surrogate */
5909 if (moreunits > 1) {
5910 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005911 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005912 /* integer overflow */
5913 PyErr_NoMemory();
5914 goto error;
5915 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005916 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005917 goto error;
5918 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5919 }
5920
5921 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005922 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005923 out += moreunits;
5924 } else /* rep is unicode */ {
5925 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5926 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5927 &out, native_ordering);
5928 }
5929
5930 Py_CLEAR(rep);
5931 }
5932
5933 /* Cut back to size actually needed. This is necessary for, for example,
5934 encoding of a string containing isolated surrogates and the 'ignore' handler
5935 is used. */
5936 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5937 if (nsize != PyBytes_GET_SIZE(v))
5938 _PyBytes_Resize(&v, nsize);
5939 Py_XDECREF(errorHandler);
5940 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005941 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005942 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005943 error:
5944 Py_XDECREF(rep);
5945 Py_XDECREF(errorHandler);
5946 Py_XDECREF(exc);
5947 Py_XDECREF(v);
5948 return NULL;
5949#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005950}
5951
Alexander Belopolsky40018472011-02-26 01:02:56 +00005952PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005953PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5954 Py_ssize_t size,
5955 const char *errors,
5956 int byteorder)
5957{
5958 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005959 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005960 if (tmp == NULL)
5961 return NULL;
5962 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5963 Py_DECREF(tmp);
5964 return result;
5965}
5966
5967PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005968PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005970 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971}
5972
5973/* --- Unicode Escape Codec ----------------------------------------------- */
5974
Fredrik Lundh06d12682001-01-24 07:59:11 +00005975static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005976
Alexander Belopolsky40018472011-02-26 01:02:56 +00005977PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005978_PyUnicode_DecodeUnicodeEscape(const char *s,
5979 Py_ssize_t size,
5980 const char *errors,
5981 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005983 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005984 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005985 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005986 PyObject *errorHandler = NULL;
5987 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005988
Eric V. Smith42454af2016-10-31 09:22:08 -04005989 // so we can remember if we've seen an invalid escape char or not
5990 *first_invalid_escape = NULL;
5991
Victor Stinner62ec3312016-09-06 17:04:34 -07005992 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005993 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005994 }
5995 /* Escaped strings will always be longer than the resulting
5996 Unicode string, so we start with size here and then reduce the
5997 length after conversion to the true value.
5998 (but if the error callback returns a long replacement string
5999 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006000 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 writer.min_length = size;
6002 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6003 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006004 }
6005
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 end = s + size;
6007 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006008 unsigned char c = (unsigned char) *s++;
6009 Py_UCS4 ch;
6010 int count;
6011 Py_ssize_t startinpos;
6012 Py_ssize_t endinpos;
6013 const char *message;
6014
6015#define WRITE_ASCII_CHAR(ch) \
6016 do { \
6017 assert(ch <= 127); \
6018 assert(writer.pos < writer.size); \
6019 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6020 } while(0)
6021
6022#define WRITE_CHAR(ch) \
6023 do { \
6024 if (ch <= writer.maxchar) { \
6025 assert(writer.pos < writer.size); \
6026 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6027 } \
6028 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6029 goto onError; \
6030 } \
6031 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006032
6033 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006034 if (c != '\\') {
6035 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006036 continue;
6037 }
6038
Victor Stinner62ec3312016-09-06 17:04:34 -07006039 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006040 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006041 if (s >= end) {
6042 message = "\\ at end of string";
6043 goto error;
6044 }
6045 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006046
Victor Stinner62ec3312016-09-06 17:04:34 -07006047 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006048 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049
Benjamin Peterson29060642009-01-31 22:14:21 +00006050 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006051 case '\n': continue;
6052 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6053 case '\'': WRITE_ASCII_CHAR('\''); continue;
6054 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6055 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006056 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006057 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6058 case 't': WRITE_ASCII_CHAR('\t'); continue;
6059 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6060 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006061 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006062 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006063 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006064 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006065
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067 case '0': case '1': case '2': case '3':
6068 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006069 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006070 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006071 ch = (ch<<3) + *s++ - '0';
6072 if (s < end && '0' <= *s && *s <= '7') {
6073 ch = (ch<<3) + *s++ - '0';
6074 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006075 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006076 WRITE_CHAR(ch);
6077 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078
Benjamin Peterson29060642009-01-31 22:14:21 +00006079 /* hex escapes */
6080 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006081 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006082 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006083 message = "truncated \\xXX escape";
6084 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085
Benjamin Peterson29060642009-01-31 22:14:21 +00006086 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006087 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006088 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006089 message = "truncated \\uXXXX escape";
6090 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006091
Benjamin Peterson29060642009-01-31 22:14:21 +00006092 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006093 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006094 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006095 message = "truncated \\UXXXXXXXX escape";
6096 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006097 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006098 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006099 ch <<= 4;
6100 if (c >= '0' && c <= '9') {
6101 ch += c - '0';
6102 }
6103 else if (c >= 'a' && c <= 'f') {
6104 ch += c - ('a' - 10);
6105 }
6106 else if (c >= 'A' && c <= 'F') {
6107 ch += c - ('A' - 10);
6108 }
6109 else {
6110 break;
6111 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006112 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006113 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006114 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006115 }
6116
6117 /* when we get here, ch is a 32-bit unicode character */
6118 if (ch > MAX_UNICODE) {
6119 message = "illegal Unicode character";
6120 goto error;
6121 }
6122
6123 WRITE_CHAR(ch);
6124 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006125
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006127 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006128 if (ucnhash_CAPI == NULL) {
6129 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006130 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6131 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006132 if (ucnhash_CAPI == NULL) {
6133 PyErr_SetString(
6134 PyExc_UnicodeError,
6135 "\\N escapes not supported (can't load unicodedata module)"
6136 );
6137 goto onError;
6138 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006139 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006140
6141 message = "malformed \\N character escape";
Gregory P. Smith746b2d32018-11-13 13:16:54 -08006142 if (s < end && *s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006143 const char *start = ++s;
6144 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006145 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006146 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006147 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006148 namelen = s - start;
6149 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006150 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006151 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006152 ch = 0xffffffff; /* in case 'getcode' messes up */
6153 if (namelen <= INT_MAX &&
6154 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6155 &ch, 0)) {
6156 assert(ch <= MAX_UNICODE);
6157 WRITE_CHAR(ch);
6158 continue;
6159 }
6160 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006161 }
6162 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006163 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006164
6165 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006166 if (*first_invalid_escape == NULL) {
6167 *first_invalid_escape = s-1; /* Back up one char, since we've
6168 already incremented s. */
6169 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006170 WRITE_ASCII_CHAR('\\');
6171 WRITE_CHAR(c);
6172 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006173 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006174
6175 error:
6176 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006177 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006178 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006179 errors, &errorHandler,
6180 "unicodeescape", message,
6181 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006182 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006183 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006184 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006185 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006186
6187#undef WRITE_ASCII_CHAR
6188#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006190
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006191 Py_XDECREF(errorHandler);
6192 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006193 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006194
Benjamin Peterson29060642009-01-31 22:14:21 +00006195 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006196 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006197 Py_XDECREF(errorHandler);
6198 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199 return NULL;
6200}
6201
Eric V. Smith42454af2016-10-31 09:22:08 -04006202PyObject *
6203PyUnicode_DecodeUnicodeEscape(const char *s,
6204 Py_ssize_t size,
6205 const char *errors)
6206{
6207 const char *first_invalid_escape;
6208 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6209 &first_invalid_escape);
6210 if (result == NULL)
6211 return NULL;
6212 if (first_invalid_escape != NULL) {
6213 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6214 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006215 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006216 Py_DECREF(result);
6217 return NULL;
6218 }
6219 }
6220 return result;
6221}
6222
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006223/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006224
Alexander Belopolsky40018472011-02-26 01:02:56 +00006225PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006226PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006228 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006229 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006231 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006232 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006233 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006234
Ezio Melottie7f90372012-10-05 03:33:31 +03006235 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006236 escape.
6237
Ezio Melottie7f90372012-10-05 03:33:31 +03006238 For UCS1 strings it's '\xxx', 4 bytes per source character.
6239 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6240 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006241 */
6242
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006243 if (!PyUnicode_Check(unicode)) {
6244 PyErr_BadArgument();
6245 return NULL;
6246 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006247 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006248 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 }
Victor Stinner358af132015-10-12 22:36:57 +02006250
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006251 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006252 if (len == 0) {
6253 return PyBytes_FromStringAndSize(NULL, 0);
6254 }
6255
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006256 kind = PyUnicode_KIND(unicode);
6257 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006258 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6259 bytes, and 1 byte characters 4. */
6260 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006261 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006262 return PyErr_NoMemory();
6263 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006264 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006265 if (repr == NULL) {
6266 return NULL;
6267 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006268
Victor Stinner62ec3312016-09-06 17:04:34 -07006269 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006270 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006271 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006272
Victor Stinner62ec3312016-09-06 17:04:34 -07006273 /* U+0000-U+00ff range */
6274 if (ch < 0x100) {
6275 if (ch >= ' ' && ch < 127) {
6276 if (ch != '\\') {
6277 /* Copy printable US ASCII as-is */
6278 *p++ = (char) ch;
6279 }
6280 /* Escape backslashes */
6281 else {
6282 *p++ = '\\';
6283 *p++ = '\\';
6284 }
6285 }
Victor Stinner358af132015-10-12 22:36:57 +02006286
Victor Stinner62ec3312016-09-06 17:04:34 -07006287 /* Map special whitespace to '\t', \n', '\r' */
6288 else if (ch == '\t') {
6289 *p++ = '\\';
6290 *p++ = 't';
6291 }
6292 else if (ch == '\n') {
6293 *p++ = '\\';
6294 *p++ = 'n';
6295 }
6296 else if (ch == '\r') {
6297 *p++ = '\\';
6298 *p++ = 'r';
6299 }
6300
6301 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6302 else {
6303 *p++ = '\\';
6304 *p++ = 'x';
6305 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6306 *p++ = Py_hexdigits[ch & 0x000F];
6307 }
Tim Petersced69f82003-09-16 20:30:58 +00006308 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006309 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006310 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311 *p++ = '\\';
6312 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006313 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6314 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6315 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6316 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006317 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006318 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6319 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006320
Victor Stinner62ec3312016-09-06 17:04:34 -07006321 /* Make sure that the first two digits are zero */
6322 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006323 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006324 *p++ = 'U';
6325 *p++ = '0';
6326 *p++ = '0';
6327 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6328 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6329 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6330 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6331 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6332 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006333 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006334 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006335
Victor Stinner62ec3312016-09-06 17:04:34 -07006336 assert(p - PyBytes_AS_STRING(repr) > 0);
6337 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6338 return NULL;
6339 }
6340 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006341}
6342
Alexander Belopolsky40018472011-02-26 01:02:56 +00006343PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006344PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6345 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006346{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006347 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006348 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006349 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006350 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006351 }
6352
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006353 result = PyUnicode_AsUnicodeEscapeString(tmp);
6354 Py_DECREF(tmp);
6355 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006356}
6357
6358/* --- Raw Unicode Escape Codec ------------------------------------------- */
6359
Alexander Belopolsky40018472011-02-26 01:02:56 +00006360PyObject *
6361PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006362 Py_ssize_t size,
6363 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006364{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006365 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006366 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006367 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006368 PyObject *errorHandler = NULL;
6369 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006370
Victor Stinner62ec3312016-09-06 17:04:34 -07006371 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006372 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006373 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006374
Guido van Rossumd57fd912000-03-10 22:53:23 +00006375 /* Escaped strings will always be longer than the resulting
6376 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006377 length after conversion to the true value. (But decoding error
6378 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006379 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006380 writer.min_length = size;
6381 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6382 goto onError;
6383 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006384
Guido van Rossumd57fd912000-03-10 22:53:23 +00006385 end = s + size;
6386 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006387 unsigned char c = (unsigned char) *s++;
6388 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006389 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006390 Py_ssize_t startinpos;
6391 Py_ssize_t endinpos;
6392 const char *message;
6393
6394#define WRITE_CHAR(ch) \
6395 do { \
6396 if (ch <= writer.maxchar) { \
6397 assert(writer.pos < writer.size); \
6398 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6399 } \
6400 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6401 goto onError; \
6402 } \
6403 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006404
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006406 if (c != '\\' || s >= end) {
6407 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006409 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006410
Victor Stinner62ec3312016-09-06 17:04:34 -07006411 c = (unsigned char) *s++;
6412 if (c == 'u') {
6413 count = 4;
6414 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006415 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006416 else if (c == 'U') {
6417 count = 8;
6418 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006419 }
6420 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006421 assert(writer.pos < writer.size);
6422 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6423 WRITE_CHAR(c);
6424 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006425 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006426 startinpos = s - starts - 2;
6427
6428 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6429 for (ch = 0; count && s < end; ++s, --count) {
6430 c = (unsigned char)*s;
6431 ch <<= 4;
6432 if (c >= '0' && c <= '9') {
6433 ch += c - '0';
6434 }
6435 else if (c >= 'a' && c <= 'f') {
6436 ch += c - ('a' - 10);
6437 }
6438 else if (c >= 'A' && c <= 'F') {
6439 ch += c - ('A' - 10);
6440 }
6441 else {
6442 break;
6443 }
6444 }
6445 if (!count) {
6446 if (ch <= MAX_UNICODE) {
6447 WRITE_CHAR(ch);
6448 continue;
6449 }
6450 message = "\\Uxxxxxxxx out of range";
6451 }
6452
6453 endinpos = s-starts;
6454 writer.min_length = end - s + writer.pos;
6455 if (unicode_decode_call_errorhandler_writer(
6456 errors, &errorHandler,
6457 "rawunicodeescape", message,
6458 &starts, &end, &startinpos, &endinpos, &exc, &s,
6459 &writer)) {
6460 goto onError;
6461 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006462 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006463
6464#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006465 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006466 Py_XDECREF(errorHandler);
6467 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006468 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006469
Benjamin Peterson29060642009-01-31 22:14:21 +00006470 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006471 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006472 Py_XDECREF(errorHandler);
6473 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006474 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006475
Guido van Rossumd57fd912000-03-10 22:53:23 +00006476}
6477
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006478
Alexander Belopolsky40018472011-02-26 01:02:56 +00006479PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006480PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006481{
Victor Stinner62ec3312016-09-06 17:04:34 -07006482 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006483 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006484 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006485 int kind;
6486 void *data;
6487 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006488
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006489 if (!PyUnicode_Check(unicode)) {
6490 PyErr_BadArgument();
6491 return NULL;
6492 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006493 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006494 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006495 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006496 kind = PyUnicode_KIND(unicode);
6497 data = PyUnicode_DATA(unicode);
6498 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006499 if (kind == PyUnicode_1BYTE_KIND) {
6500 return PyBytes_FromStringAndSize(data, len);
6501 }
Victor Stinner0e368262011-11-10 20:12:49 +01006502
Victor Stinner62ec3312016-09-06 17:04:34 -07006503 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6504 bytes, and 1 byte characters 4. */
6505 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006506
Victor Stinner62ec3312016-09-06 17:04:34 -07006507 if (len > PY_SSIZE_T_MAX / expandsize) {
6508 return PyErr_NoMemory();
6509 }
6510 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6511 if (repr == NULL) {
6512 return NULL;
6513 }
6514 if (len == 0) {
6515 return repr;
6516 }
6517
6518 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006519 for (pos = 0; pos < len; pos++) {
6520 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006521
Victor Stinner62ec3312016-09-06 17:04:34 -07006522 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6523 if (ch < 0x100) {
6524 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006525 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006526 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006527 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006528 *p++ = '\\';
6529 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006530 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6531 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6532 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6533 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006534 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006535 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6536 else {
6537 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6538 *p++ = '\\';
6539 *p++ = 'U';
6540 *p++ = '0';
6541 *p++ = '0';
6542 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6543 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6544 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6545 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6546 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6547 *p++ = Py_hexdigits[ch & 15];
6548 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006549 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006550
Victor Stinner62ec3312016-09-06 17:04:34 -07006551 assert(p > PyBytes_AS_STRING(repr));
6552 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6553 return NULL;
6554 }
6555 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006556}
6557
Alexander Belopolsky40018472011-02-26 01:02:56 +00006558PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006559PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6560 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006561{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006562 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006563 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006564 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006565 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006566 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6567 Py_DECREF(tmp);
6568 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006569}
6570
6571/* --- Latin-1 Codec ------------------------------------------------------ */
6572
Alexander Belopolsky40018472011-02-26 01:02:56 +00006573PyObject *
6574PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006575 Py_ssize_t size,
6576 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006577{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006578 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006579 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006580}
6581
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006582/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006583static void
6584make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006585 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006586 PyObject *unicode,
6587 Py_ssize_t startpos, Py_ssize_t endpos,
6588 const char *reason)
6589{
6590 if (*exceptionObject == NULL) {
6591 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006592 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006593 encoding, unicode, startpos, endpos, reason);
6594 }
6595 else {
6596 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6597 goto onError;
6598 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6599 goto onError;
6600 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6601 goto onError;
6602 return;
6603 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006604 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006605 }
6606}
6607
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006608/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006609static void
6610raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006611 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006612 PyObject *unicode,
6613 Py_ssize_t startpos, Py_ssize_t endpos,
6614 const char *reason)
6615{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006616 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006617 encoding, unicode, startpos, endpos, reason);
6618 if (*exceptionObject != NULL)
6619 PyCodec_StrictErrors(*exceptionObject);
6620}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006621
6622/* error handling callback helper:
6623 build arguments, call the callback and check the arguments,
6624 put the result into newpos and return the replacement string, which
6625 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006626static PyObject *
6627unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006628 PyObject **errorHandler,
6629 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006630 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006631 Py_ssize_t startpos, Py_ssize_t endpos,
6632 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006633{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006634 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006636 PyObject *restuple;
6637 PyObject *resunicode;
6638
6639 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006640 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006641 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006642 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006643 }
6644
Benjamin Petersonbac79492012-01-14 13:34:47 -05006645 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646 return NULL;
6647 len = PyUnicode_GET_LENGTH(unicode);
6648
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006649 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006650 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006651 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006653
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006654 restuple = PyObject_CallFunctionObjArgs(
6655 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006656 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006658 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006659 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006660 Py_DECREF(restuple);
6661 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006662 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006663 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006664 &resunicode, newpos)) {
6665 Py_DECREF(restuple);
6666 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006667 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006668 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6669 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6670 Py_DECREF(restuple);
6671 return NULL;
6672 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006674 *newpos = len + *newpos;
6675 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006676 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006677 Py_DECREF(restuple);
6678 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006679 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006680 Py_INCREF(resunicode);
6681 Py_DECREF(restuple);
6682 return resunicode;
6683}
6684
Alexander Belopolsky40018472011-02-26 01:02:56 +00006685static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006686unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006687 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006688 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006689{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006690 /* input state */
6691 Py_ssize_t pos=0, size;
6692 int kind;
6693 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006694 /* pointer into the output */
6695 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006696 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6697 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006698 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006699 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006700 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006701 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006702 /* output object */
6703 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704
Benjamin Petersonbac79492012-01-14 13:34:47 -05006705 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006706 return NULL;
6707 size = PyUnicode_GET_LENGTH(unicode);
6708 kind = PyUnicode_KIND(unicode);
6709 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006710 /* allocate enough for a simple encoding without
6711 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006712 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006713 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006714
6715 _PyBytesWriter_Init(&writer);
6716 str = _PyBytesWriter_Alloc(&writer, size);
6717 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006718 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006719
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006720 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006721 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006722
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006724 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006726 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006727 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006728 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006730 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006732 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006733 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006734 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006735
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006736 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006737 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006738
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006739 /* Only overallocate the buffer if it's not the last write */
6740 writer.overallocate = (collend < size);
6741
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006743 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006744 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02006745
6746 switch (error_handler) {
6747 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006748 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006749 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006750
6751 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006752 memset(str, '?', collend - collstart);
6753 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006754 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006755 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006756 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006757 break;
Victor Stinner50149202015-09-22 00:26:54 +02006758
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006759 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006760 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006761 writer.min_size -= (collend - collstart);
6762 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006763 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006764 if (str == NULL)
6765 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006766 pos = collend;
6767 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006768
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006769 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006770 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006771 writer.min_size -= (collend - collstart);
6772 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006773 unicode, collstart, collend);
6774 if (str == NULL)
6775 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006776 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006777 break;
Victor Stinner50149202015-09-22 00:26:54 +02006778
Victor Stinnerc3713e92015-09-29 12:32:13 +02006779 case _Py_ERROR_SURROGATEESCAPE:
6780 for (i = collstart; i < collend; ++i) {
6781 ch = PyUnicode_READ(kind, data, i);
6782 if (ch < 0xdc80 || 0xdcff < ch) {
6783 /* Not a UTF-8b surrogate */
6784 break;
6785 }
6786 *str++ = (char)(ch - 0xdc00);
6787 ++pos;
6788 }
6789 if (i >= collend)
6790 break;
6791 collstart = pos;
6792 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006793 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006794
Benjamin Peterson29060642009-01-31 22:14:21 +00006795 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006796 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6797 encoding, reason, unicode, &exc,
6798 collstart, collend, &newpos);
6799 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006800 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006801
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006802 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006803 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006804
Victor Stinner6bd525b2015-10-09 13:10:05 +02006805 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006806 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006807 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006808 PyBytes_AS_STRING(rep),
6809 PyBytes_GET_SIZE(rep));
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006810 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006811 else {
6812 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006813
Victor Stinner6bd525b2015-10-09 13:10:05 +02006814 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006815 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006816
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006817 if (limit == 256 ?
6818 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6819 !PyUnicode_IS_ASCII(rep))
6820 {
6821 /* Not all characters are smaller than limit */
6822 raise_encode_exception(&exc, encoding, unicode,
6823 collstart, collend, reason);
6824 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006825 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006826 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6827 str = _PyBytesWriter_WriteBytes(&writer, str,
6828 PyUnicode_DATA(rep),
6829 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006830 }
Alexey Izbyshev74a307d2018-08-19 21:52:04 +03006831 if (str == NULL)
6832 goto onError;
6833
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006834 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006835 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006836 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006837
6838 /* If overallocation was disabled, ensure that it was the last
6839 write. Otherwise, we missed an optimization */
6840 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006841 }
6842 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006843
Victor Stinner50149202015-09-22 00:26:54 +02006844 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006845 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006846 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006847
6848 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006849 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006850 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006851 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006852 Py_XDECREF(exc);
6853 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006854}
6855
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006856/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006857PyObject *
6858PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006859 Py_ssize_t size,
6860 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006861{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006862 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006863 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006864 if (unicode == NULL)
6865 return NULL;
6866 result = unicode_encode_ucs1(unicode, errors, 256);
6867 Py_DECREF(unicode);
6868 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006869}
6870
Alexander Belopolsky40018472011-02-26 01:02:56 +00006871PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006872_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006873{
6874 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006875 PyErr_BadArgument();
6876 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006878 if (PyUnicode_READY(unicode) == -1)
6879 return NULL;
6880 /* Fast path: if it is a one-byte string, construct
6881 bytes object directly. */
6882 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6883 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6884 PyUnicode_GET_LENGTH(unicode));
6885 /* Non-Latin-1 characters present. Defer to above function to
6886 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006887 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006888}
6889
6890PyObject*
6891PyUnicode_AsLatin1String(PyObject *unicode)
6892{
6893 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006894}
6895
6896/* --- 7-bit ASCII Codec -------------------------------------------------- */
6897
Alexander Belopolsky40018472011-02-26 01:02:56 +00006898PyObject *
6899PyUnicode_DecodeASCII(const char *s,
6900 Py_ssize_t size,
6901 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006902{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006903 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006904 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006905 int kind;
6906 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006907 Py_ssize_t startinpos;
6908 Py_ssize_t endinpos;
6909 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006910 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006911 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006912 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006913 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006914
Guido van Rossumd57fd912000-03-10 22:53:23 +00006915 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006916 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006917
Guido van Rossumd57fd912000-03-10 22:53:23 +00006918 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006919 if (size == 1 && (unsigned char)s[0] < 128)
6920 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006921
Victor Stinner8f674cc2013-04-17 23:02:17 +02006922 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006923 writer.min_length = size;
6924 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006925 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006926
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006927 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006928 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006929 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006930 writer.pos = outpos;
6931 if (writer.pos == size)
6932 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006933
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006934 s += writer.pos;
6935 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006936 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02006937 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00006938 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006939 PyUnicode_WRITE(kind, data, writer.pos, c);
6940 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00006941 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006942 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00006943 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006944
6945 /* byte outsize range 0x00..0x7f: call the error handler */
6946
6947 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006948 error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006949
6950 switch (error_handler)
6951 {
6952 case _Py_ERROR_REPLACE:
6953 case _Py_ERROR_SURROGATEESCAPE:
6954 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02006955 but we may switch to UCS2 at the first write */
6956 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
6957 goto onError;
6958 kind = writer.kind;
6959 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006960
6961 if (error_handler == _Py_ERROR_REPLACE)
6962 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
6963 else
6964 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
6965 writer.pos++;
6966 ++s;
6967 break;
6968
6969 case _Py_ERROR_IGNORE:
6970 ++s;
6971 break;
6972
6973 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 startinpos = s-starts;
6975 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006976 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02006977 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00006978 "ascii", "ordinal not in range(128)",
6979 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006980 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00006981 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006982 kind = writer.kind;
6983 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00006984 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006985 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02006986 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006987 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006988 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006989
Benjamin Peterson29060642009-01-31 22:14:21 +00006990 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006991 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02006992 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006993 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006994 return NULL;
6995}
6996
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006997/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006998PyObject *
6999PyUnicode_EncodeASCII(const Py_UNICODE *p,
7000 Py_ssize_t size,
7001 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007002{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007003 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007004 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007005 if (unicode == NULL)
7006 return NULL;
7007 result = unicode_encode_ucs1(unicode, errors, 128);
7008 Py_DECREF(unicode);
7009 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007010}
7011
Alexander Belopolsky40018472011-02-26 01:02:56 +00007012PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007013_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007014{
7015 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007016 PyErr_BadArgument();
7017 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007018 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007019 if (PyUnicode_READY(unicode) == -1)
7020 return NULL;
7021 /* Fast path: if it is an ASCII-only string, construct bytes object
7022 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007023 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007024 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7025 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007026 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007027}
7028
7029PyObject *
7030PyUnicode_AsASCIIString(PyObject *unicode)
7031{
7032 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007033}
7034
Steve Dowercc16be82016-09-08 10:35:16 -07007035#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007036
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007037/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007038
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007039#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040#define NEED_RETRY
7041#endif
7042
Victor Stinner3a50e702011-10-18 21:21:00 +02007043#ifndef WC_ERR_INVALID_CHARS
7044# define WC_ERR_INVALID_CHARS 0x0080
7045#endif
7046
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007047static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007048code_page_name(UINT code_page, PyObject **obj)
7049{
7050 *obj = NULL;
7051 if (code_page == CP_ACP)
7052 return "mbcs";
7053 if (code_page == CP_UTF7)
7054 return "CP_UTF7";
7055 if (code_page == CP_UTF8)
7056 return "CP_UTF8";
7057
7058 *obj = PyBytes_FromFormat("cp%u", code_page);
7059 if (*obj == NULL)
7060 return NULL;
7061 return PyBytes_AS_STRING(*obj);
7062}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007063
Victor Stinner3a50e702011-10-18 21:21:00 +02007064static DWORD
7065decode_code_page_flags(UINT code_page)
7066{
7067 if (code_page == CP_UTF7) {
7068 /* The CP_UTF7 decoder only supports flags=0 */
7069 return 0;
7070 }
7071 else
7072 return MB_ERR_INVALID_CHARS;
7073}
7074
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007075/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007076 * Decode a byte string from a Windows code page into unicode object in strict
7077 * mode.
7078 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007079 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7080 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007082static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007083decode_code_page_strict(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007084 wchar_t **buf,
7085 Py_ssize_t *bufsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007086 const char *in,
7087 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007088{
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007089 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner24729f32011-11-10 20:31:37 +01007090 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007091 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007092
7093 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007094 assert(insize > 0);
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007095 while ((outsize = MultiByteToWideChar(code_page, flags,
7096 in, insize, NULL, 0)) <= 0)
7097 {
7098 if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
7099 goto error;
7100 }
7101 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7102 flags = 0;
7103 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007104
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007105 /* Extend a wchar_t* buffer */
7106 Py_ssize_t n = *bufsize; /* Get the current length */
7107 if (widechar_resize(buf, bufsize, n + outsize) < 0) {
7108 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007109 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007110 out = *buf + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007111
7112 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007113 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7114 if (outsize <= 0)
7115 goto error;
7116 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007117
Victor Stinner3a50e702011-10-18 21:21:00 +02007118error:
7119 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7120 return -2;
7121 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007122 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007123}
7124
Victor Stinner3a50e702011-10-18 21:21:00 +02007125/*
7126 * Decode a byte string from a code page into unicode object with an error
7127 * handler.
7128 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007129 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007130 * UnicodeDecodeError exception and returns -1 on error.
7131 */
7132static int
7133decode_code_page_errors(UINT code_page,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007134 wchar_t **buf,
7135 Py_ssize_t *bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007136 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007137 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007138{
7139 const char *startin = in;
7140 const char *endin = in + size;
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007141 DWORD flags = MB_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007142 /* Ideally, we should get reason from FormatMessage. This is the Windows
7143 2000 English version of the message. */
7144 const char *reason = "No mapping for the Unicode character exists "
7145 "in the target code page.";
7146 /* each step cannot decode more than 1 character, but a character can be
7147 represented as a surrogate pair */
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007148 wchar_t buffer[2], *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007149 int insize;
7150 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007151 PyObject *errorHandler = NULL;
7152 PyObject *exc = NULL;
7153 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007154 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 DWORD err;
7156 int ret = -1;
7157
7158 assert(size > 0);
7159
7160 encoding = code_page_name(code_page, &encoding_obj);
7161 if (encoding == NULL)
7162 return -1;
7163
Victor Stinner7d00cc12014-03-17 23:08:06 +01007164 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007165 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7166 UnicodeDecodeError. */
7167 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7168 if (exc != NULL) {
7169 PyCodec_StrictErrors(exc);
7170 Py_CLEAR(exc);
7171 }
7172 goto error;
7173 }
7174
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007175 /* Extend a wchar_t* buffer */
7176 Py_ssize_t n = *bufsize; /* Get the current length */
7177 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7178 PyErr_NoMemory();
7179 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007181 if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
7182 goto error;
Victor Stinner3a50e702011-10-18 21:21:00 +02007183 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007184 out = *buf + n;
Victor Stinner3a50e702011-10-18 21:21:00 +02007185
7186 /* Decode the byte string character per character */
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 while (in < endin)
7188 {
7189 /* Decode a character */
7190 insize = 1;
7191 do
7192 {
7193 outsize = MultiByteToWideChar(code_page, flags,
7194 in, insize,
7195 buffer, Py_ARRAY_LENGTH(buffer));
7196 if (outsize > 0)
7197 break;
7198 err = GetLastError();
Serhiy Storchakac1e2c282019-03-20 21:45:18 +02007199 if (err == ERROR_INVALID_FLAGS && flags) {
7200 /* For some code pages (e.g. UTF-7) flags must be set to 0. */
7201 flags = 0;
7202 continue;
7203 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007204 if (err != ERROR_NO_UNICODE_TRANSLATION
7205 && err != ERROR_INSUFFICIENT_BUFFER)
7206 {
7207 PyErr_SetFromWindowsErr(0);
7208 goto error;
7209 }
7210 insize++;
7211 }
7212 /* 4=maximum length of a UTF-8 sequence */
7213 while (insize <= 4 && (in + insize) <= endin);
7214
7215 if (outsize <= 0) {
7216 Py_ssize_t startinpos, endinpos, outpos;
7217
Victor Stinner7d00cc12014-03-17 23:08:06 +01007218 /* last character in partial decode? */
7219 if (in + insize >= endin && !final)
7220 break;
7221
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 startinpos = in - startin;
7223 endinpos = startinpos + 1;
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007224 outpos = out - *buf;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007225 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007226 errors, &errorHandler,
7227 encoding, reason,
7228 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007229 buf, bufsize, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 {
7231 goto error;
7232 }
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007233 out = *buf + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007234 }
7235 else {
7236 in += insize;
7237 memcpy(out, buffer, outsize * sizeof(wchar_t));
7238 out += outsize;
7239 }
7240 }
7241
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007242 /* Shrink the buffer */
7243 assert(out - *buf <= *bufsize);
7244 *bufsize = out - *buf;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007245 /* (in - startin) <= size and size is an int */
7246 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007247
7248error:
7249 Py_XDECREF(encoding_obj);
7250 Py_XDECREF(errorHandler);
7251 Py_XDECREF(exc);
7252 return ret;
7253}
7254
Victor Stinner3a50e702011-10-18 21:21:00 +02007255static PyObject *
7256decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007257 const char *s, Py_ssize_t size,
7258 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007259{
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007260 wchar_t *buf = NULL;
7261 Py_ssize_t bufsize = 0;
Victor Stinner76a31a62011-11-04 00:05:13 +01007262 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007263
Victor Stinner3a50e702011-10-18 21:21:00 +02007264 if (code_page < 0) {
7265 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7266 return NULL;
7267 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007268 if (size < 0) {
7269 PyErr_BadInternalCall();
7270 return NULL;
7271 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007272
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007274 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007275
Victor Stinner76a31a62011-11-04 00:05:13 +01007276 do
7277 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007278#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007279 if (size > INT_MAX) {
7280 chunk_size = INT_MAX;
7281 final = 0;
7282 done = 0;
7283 }
7284 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007285#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007286 {
7287 chunk_size = (int)size;
7288 final = (consumed == NULL);
7289 done = 1;
7290 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007291
Victor Stinner76a31a62011-11-04 00:05:13 +01007292 if (chunk_size == 0 && done) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007293 if (buf != NULL)
Victor Stinner76a31a62011-11-04 00:05:13 +01007294 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007295 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007296 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007297
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007298 converted = decode_code_page_strict(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007299 s, chunk_size);
7300 if (converted == -2)
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007301 converted = decode_code_page_errors(code_page, &buf, &bufsize,
Victor Stinner76a31a62011-11-04 00:05:13 +01007302 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007303 errors, final);
7304 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007305
7306 if (converted < 0) {
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007307 PyMem_Free(buf);
Victor Stinner76a31a62011-11-04 00:05:13 +01007308 return NULL;
7309 }
7310
7311 if (consumed)
7312 *consumed += converted;
7313
7314 s += converted;
7315 size -= converted;
7316 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007317
Serhiy Storchakaeeb719e2018-12-04 10:25:50 +02007318 PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
7319 PyMem_Free(buf);
7320 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007321}
7322
Alexander Belopolsky40018472011-02-26 01:02:56 +00007323PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007324PyUnicode_DecodeCodePageStateful(int code_page,
7325 const char *s,
7326 Py_ssize_t size,
7327 const char *errors,
7328 Py_ssize_t *consumed)
7329{
7330 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7331}
7332
7333PyObject *
7334PyUnicode_DecodeMBCSStateful(const char *s,
7335 Py_ssize_t size,
7336 const char *errors,
7337 Py_ssize_t *consumed)
7338{
7339 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7340}
7341
7342PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007343PyUnicode_DecodeMBCS(const char *s,
7344 Py_ssize_t size,
7345 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007346{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007347 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7348}
7349
Victor Stinner3a50e702011-10-18 21:21:00 +02007350static DWORD
7351encode_code_page_flags(UINT code_page, const char *errors)
7352{
7353 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007354 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 }
7356 else if (code_page == CP_UTF7) {
7357 /* CP_UTF7 only supports flags=0 */
7358 return 0;
7359 }
7360 else {
7361 if (errors != NULL && strcmp(errors, "replace") == 0)
7362 return 0;
7363 else
7364 return WC_NO_BEST_FIT_CHARS;
7365 }
7366}
7367
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007368/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007369 * Encode a Unicode string to a Windows code page into a byte string in strict
7370 * mode.
7371 *
7372 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007373 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007374 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007375static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007376encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007377 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007379{
Victor Stinner554f3f02010-06-16 23:33:54 +00007380 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007381 BOOL *pusedDefaultChar = &usedDefaultChar;
7382 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007383 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007384 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007385 const DWORD flags = encode_code_page_flags(code_page, NULL);
7386 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007387 /* Create a substring so that we can get the UTF-16 representation
7388 of just the slice under consideration. */
7389 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007390
Martin v. Löwis3d325192011-11-04 18:23:06 +01007391 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007392
Victor Stinner3a50e702011-10-18 21:21:00 +02007393 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007394 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007396 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007397
Victor Stinner2fc507f2011-11-04 20:06:39 +01007398 substring = PyUnicode_Substring(unicode, offset, offset+len);
7399 if (substring == NULL)
7400 return -1;
7401 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7402 if (p == NULL) {
7403 Py_DECREF(substring);
7404 return -1;
7405 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007406 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007407
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007408 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007410 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 NULL, 0,
7412 NULL, pusedDefaultChar);
7413 if (outsize <= 0)
7414 goto error;
7415 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007416 if (pusedDefaultChar && *pusedDefaultChar) {
7417 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007418 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007419 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007420
Victor Stinner3a50e702011-10-18 21:21:00 +02007421 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007422 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007424 if (*outbytes == NULL) {
7425 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007426 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007427 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007429 }
7430 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007431 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 const Py_ssize_t n = PyBytes_Size(*outbytes);
7433 if (outsize > PY_SSIZE_T_MAX - n) {
7434 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007435 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007436 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007437 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007438 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7439 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007440 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007441 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007442 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007443 }
7444
7445 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007447 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 out, outsize,
7449 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007450 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 if (outsize <= 0)
7452 goto error;
7453 if (pusedDefaultChar && *pusedDefaultChar)
7454 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007455 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007456
Victor Stinner3a50e702011-10-18 21:21:00 +02007457error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7460 return -2;
7461 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007462 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007463}
7464
Victor Stinner3a50e702011-10-18 21:21:00 +02007465/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007466 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 * error handler.
7468 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007469 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007470 * -1 on other error.
7471 */
7472static int
7473encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007474 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007475 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007476{
Victor Stinner3a50e702011-10-18 21:21:00 +02007477 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007478 Py_ssize_t pos = unicode_offset;
7479 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007480 /* Ideally, we should get reason from FormatMessage. This is the Windows
7481 2000 English version of the message. */
7482 const char *reason = "invalid character";
7483 /* 4=maximum length of a UTF-8 sequence */
7484 char buffer[4];
7485 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7486 Py_ssize_t outsize;
7487 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007488 PyObject *errorHandler = NULL;
7489 PyObject *exc = NULL;
7490 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007491 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007492 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007493 PyObject *rep;
7494 int ret = -1;
7495
7496 assert(insize > 0);
7497
7498 encoding = code_page_name(code_page, &encoding_obj);
7499 if (encoding == NULL)
7500 return -1;
7501
7502 if (errors == NULL || strcmp(errors, "strict") == 0) {
7503 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7504 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007505 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007506 if (exc != NULL) {
7507 PyCodec_StrictErrors(exc);
7508 Py_DECREF(exc);
7509 }
7510 Py_XDECREF(encoding_obj);
7511 return -1;
7512 }
7513
7514 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7515 pusedDefaultChar = &usedDefaultChar;
7516 else
7517 pusedDefaultChar = NULL;
7518
7519 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7520 PyErr_NoMemory();
7521 goto error;
7522 }
7523 outsize = insize * Py_ARRAY_LENGTH(buffer);
7524
7525 if (*outbytes == NULL) {
7526 /* Create string object */
7527 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7528 if (*outbytes == NULL)
7529 goto error;
7530 out = PyBytes_AS_STRING(*outbytes);
7531 }
7532 else {
7533 /* Extend string object */
7534 Py_ssize_t n = PyBytes_Size(*outbytes);
7535 if (n > PY_SSIZE_T_MAX - outsize) {
7536 PyErr_NoMemory();
7537 goto error;
7538 }
7539 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7540 goto error;
7541 out = PyBytes_AS_STRING(*outbytes) + n;
7542 }
7543
7544 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007545 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007546 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007547 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7548 wchar_t chars[2];
7549 int charsize;
7550 if (ch < 0x10000) {
7551 chars[0] = (wchar_t)ch;
7552 charsize = 1;
7553 }
7554 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007555 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7556 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007557 charsize = 2;
7558 }
7559
Victor Stinner3a50e702011-10-18 21:21:00 +02007560 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007561 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007562 buffer, Py_ARRAY_LENGTH(buffer),
7563 NULL, pusedDefaultChar);
7564 if (outsize > 0) {
7565 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7566 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007567 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007568 memcpy(out, buffer, outsize);
7569 out += outsize;
7570 continue;
7571 }
7572 }
7573 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7574 PyErr_SetFromWindowsErr(0);
7575 goto error;
7576 }
7577
Victor Stinner3a50e702011-10-18 21:21:00 +02007578 rep = unicode_encode_call_errorhandler(
7579 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007580 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007581 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007582 if (rep == NULL)
7583 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007584 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007585
7586 if (PyBytes_Check(rep)) {
7587 outsize = PyBytes_GET_SIZE(rep);
7588 if (outsize != 1) {
7589 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7590 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7591 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7592 Py_DECREF(rep);
7593 goto error;
7594 }
7595 out = PyBytes_AS_STRING(*outbytes) + offset;
7596 }
7597 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7598 out += outsize;
7599 }
7600 else {
7601 Py_ssize_t i;
7602 enum PyUnicode_Kind kind;
7603 void *data;
7604
Benjamin Petersonbac79492012-01-14 13:34:47 -05007605 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007606 Py_DECREF(rep);
7607 goto error;
7608 }
7609
7610 outsize = PyUnicode_GET_LENGTH(rep);
7611 if (outsize != 1) {
7612 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7613 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7614 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7615 Py_DECREF(rep);
7616 goto error;
7617 }
7618 out = PyBytes_AS_STRING(*outbytes) + offset;
7619 }
7620 kind = PyUnicode_KIND(rep);
7621 data = PyUnicode_DATA(rep);
7622 for (i=0; i < outsize; i++) {
7623 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7624 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007625 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007626 encoding, unicode,
7627 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007628 "unable to encode error handler result to ASCII");
7629 Py_DECREF(rep);
7630 goto error;
7631 }
7632 *out = (unsigned char)ch;
7633 out++;
7634 }
7635 }
7636 Py_DECREF(rep);
7637 }
7638 /* write a NUL byte */
7639 *out = 0;
7640 outsize = out - PyBytes_AS_STRING(*outbytes);
7641 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7642 if (_PyBytes_Resize(outbytes, outsize) < 0)
7643 goto error;
7644 ret = 0;
7645
7646error:
7647 Py_XDECREF(encoding_obj);
7648 Py_XDECREF(errorHandler);
7649 Py_XDECREF(exc);
7650 return ret;
7651}
7652
Victor Stinner3a50e702011-10-18 21:21:00 +02007653static PyObject *
7654encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007655 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007656 const char *errors)
7657{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007658 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007659 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007660 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007661 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007662
Victor Stinner29dacf22015-01-26 16:41:32 +01007663 if (!PyUnicode_Check(unicode)) {
7664 PyErr_BadArgument();
7665 return NULL;
7666 }
7667
Benjamin Petersonbac79492012-01-14 13:34:47 -05007668 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007669 return NULL;
7670 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007671
Victor Stinner3a50e702011-10-18 21:21:00 +02007672 if (code_page < 0) {
7673 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7674 return NULL;
7675 }
7676
Martin v. Löwis3d325192011-11-04 18:23:06 +01007677 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007678 return PyBytes_FromStringAndSize(NULL, 0);
7679
Victor Stinner7581cef2011-11-03 22:32:33 +01007680 offset = 0;
7681 do
7682 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007683#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007684 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007685 chunks. */
7686 if (len > INT_MAX/2) {
7687 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007688 done = 0;
7689 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007690 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007691#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007692 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007693 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007694 done = 1;
7695 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007696
Victor Stinner76a31a62011-11-04 00:05:13 +01007697 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007698 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007699 errors);
7700 if (ret == -2)
7701 ret = encode_code_page_errors(code_page, &outbytes,
7702 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007703 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007704 if (ret < 0) {
7705 Py_XDECREF(outbytes);
7706 return NULL;
7707 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007708
Victor Stinner7581cef2011-11-03 22:32:33 +01007709 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007710 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007711 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007712
Victor Stinner3a50e702011-10-18 21:21:00 +02007713 return outbytes;
7714}
7715
7716PyObject *
7717PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7718 Py_ssize_t size,
7719 const char *errors)
7720{
Victor Stinner7581cef2011-11-03 22:32:33 +01007721 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007722 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007723 if (unicode == NULL)
7724 return NULL;
7725 res = encode_code_page(CP_ACP, unicode, errors);
7726 Py_DECREF(unicode);
7727 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007728}
7729
7730PyObject *
7731PyUnicode_EncodeCodePage(int code_page,
7732 PyObject *unicode,
7733 const char *errors)
7734{
Victor Stinner7581cef2011-11-03 22:32:33 +01007735 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007736}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007737
Alexander Belopolsky40018472011-02-26 01:02:56 +00007738PyObject *
7739PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007740{
Victor Stinner7581cef2011-11-03 22:32:33 +01007741 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007742}
7743
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007744#undef NEED_RETRY
7745
Steve Dowercc16be82016-09-08 10:35:16 -07007746#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007747
Guido van Rossumd57fd912000-03-10 22:53:23 +00007748/* --- Character Mapping Codec -------------------------------------------- */
7749
Victor Stinnerfb161b12013-04-18 01:44:27 +02007750static int
7751charmap_decode_string(const char *s,
7752 Py_ssize_t size,
7753 PyObject *mapping,
7754 const char *errors,
7755 _PyUnicodeWriter *writer)
7756{
7757 const char *starts = s;
7758 const char *e;
7759 Py_ssize_t startinpos, endinpos;
7760 PyObject *errorHandler = NULL, *exc = NULL;
7761 Py_ssize_t maplen;
7762 enum PyUnicode_Kind mapkind;
7763 void *mapdata;
7764 Py_UCS4 x;
7765 unsigned char ch;
7766
7767 if (PyUnicode_READY(mapping) == -1)
7768 return -1;
7769
7770 maplen = PyUnicode_GET_LENGTH(mapping);
7771 mapdata = PyUnicode_DATA(mapping);
7772 mapkind = PyUnicode_KIND(mapping);
7773
7774 e = s + size;
7775
7776 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7777 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7778 * is disabled in encoding aliases, latin1 is preferred because
7779 * its implementation is faster. */
7780 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7781 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7782 Py_UCS4 maxchar = writer->maxchar;
7783
7784 assert (writer->kind == PyUnicode_1BYTE_KIND);
7785 while (s < e) {
7786 ch = *s;
7787 x = mapdata_ucs1[ch];
7788 if (x > maxchar) {
7789 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7790 goto onError;
7791 maxchar = writer->maxchar;
7792 outdata = (Py_UCS1 *)writer->data;
7793 }
7794 outdata[writer->pos] = x;
7795 writer->pos++;
7796 ++s;
7797 }
7798 return 0;
7799 }
7800
7801 while (s < e) {
7802 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7803 enum PyUnicode_Kind outkind = writer->kind;
7804 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7805 if (outkind == PyUnicode_1BYTE_KIND) {
7806 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7807 Py_UCS4 maxchar = writer->maxchar;
7808 while (s < e) {
7809 ch = *s;
7810 x = mapdata_ucs2[ch];
7811 if (x > maxchar)
7812 goto Error;
7813 outdata[writer->pos] = x;
7814 writer->pos++;
7815 ++s;
7816 }
7817 break;
7818 }
7819 else if (outkind == PyUnicode_2BYTE_KIND) {
7820 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7821 while (s < e) {
7822 ch = *s;
7823 x = mapdata_ucs2[ch];
7824 if (x == 0xFFFE)
7825 goto Error;
7826 outdata[writer->pos] = x;
7827 writer->pos++;
7828 ++s;
7829 }
7830 break;
7831 }
7832 }
7833 ch = *s;
7834
7835 if (ch < maplen)
7836 x = PyUnicode_READ(mapkind, mapdata, ch);
7837 else
7838 x = 0xfffe; /* invalid value */
7839Error:
7840 if (x == 0xfffe)
7841 {
7842 /* undefined mapping */
7843 startinpos = s-starts;
7844 endinpos = startinpos+1;
7845 if (unicode_decode_call_errorhandler_writer(
7846 errors, &errorHandler,
7847 "charmap", "character maps to <undefined>",
7848 &starts, &e, &startinpos, &endinpos, &exc, &s,
7849 writer)) {
7850 goto onError;
7851 }
7852 continue;
7853 }
7854
7855 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7856 goto onError;
7857 ++s;
7858 }
7859 Py_XDECREF(errorHandler);
7860 Py_XDECREF(exc);
7861 return 0;
7862
7863onError:
7864 Py_XDECREF(errorHandler);
7865 Py_XDECREF(exc);
7866 return -1;
7867}
7868
7869static int
7870charmap_decode_mapping(const char *s,
7871 Py_ssize_t size,
7872 PyObject *mapping,
7873 const char *errors,
7874 _PyUnicodeWriter *writer)
7875{
7876 const char *starts = s;
7877 const char *e;
7878 Py_ssize_t startinpos, endinpos;
7879 PyObject *errorHandler = NULL, *exc = NULL;
7880 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007881 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007882
7883 e = s + size;
7884
7885 while (s < e) {
7886 ch = *s;
7887
7888 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7889 key = PyLong_FromLong((long)ch);
7890 if (key == NULL)
7891 goto onError;
7892
7893 item = PyObject_GetItem(mapping, key);
7894 Py_DECREF(key);
7895 if (item == NULL) {
7896 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7897 /* No mapping found means: mapping is undefined. */
7898 PyErr_Clear();
7899 goto Undefined;
7900 } else
7901 goto onError;
7902 }
7903
7904 /* Apply mapping */
7905 if (item == Py_None)
7906 goto Undefined;
7907 if (PyLong_Check(item)) {
7908 long value = PyLong_AS_LONG(item);
7909 if (value == 0xFFFE)
7910 goto Undefined;
7911 if (value < 0 || value > MAX_UNICODE) {
7912 PyErr_Format(PyExc_TypeError,
7913 "character mapping must be in range(0x%lx)",
7914 (unsigned long)MAX_UNICODE + 1);
7915 goto onError;
7916 }
7917
7918 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7919 goto onError;
7920 }
7921 else if (PyUnicode_Check(item)) {
7922 if (PyUnicode_READY(item) == -1)
7923 goto onError;
7924 if (PyUnicode_GET_LENGTH(item) == 1) {
7925 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
7926 if (value == 0xFFFE)
7927 goto Undefined;
7928 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7929 goto onError;
7930 }
7931 else {
7932 writer->overallocate = 1;
7933 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
7934 goto onError;
7935 }
7936 }
7937 else {
7938 /* wrong return value */
7939 PyErr_SetString(PyExc_TypeError,
7940 "character mapping must return integer, None or str");
7941 goto onError;
7942 }
7943 Py_CLEAR(item);
7944 ++s;
7945 continue;
7946
7947Undefined:
7948 /* undefined mapping */
7949 Py_CLEAR(item);
7950 startinpos = s-starts;
7951 endinpos = startinpos+1;
7952 if (unicode_decode_call_errorhandler_writer(
7953 errors, &errorHandler,
7954 "charmap", "character maps to <undefined>",
7955 &starts, &e, &startinpos, &endinpos, &exc, &s,
7956 writer)) {
7957 goto onError;
7958 }
7959 }
7960 Py_XDECREF(errorHandler);
7961 Py_XDECREF(exc);
7962 return 0;
7963
7964onError:
7965 Py_XDECREF(item);
7966 Py_XDECREF(errorHandler);
7967 Py_XDECREF(exc);
7968 return -1;
7969}
7970
Alexander Belopolsky40018472011-02-26 01:02:56 +00007971PyObject *
7972PyUnicode_DecodeCharmap(const char *s,
7973 Py_ssize_t size,
7974 PyObject *mapping,
7975 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007976{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007977 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00007978
Guido van Rossumd57fd912000-03-10 22:53:23 +00007979 /* Default to Latin-1 */
7980 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007981 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007982
Guido van Rossumd57fd912000-03-10 22:53:23 +00007983 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02007984 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02007985 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02007986 writer.min_length = size;
7987 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007988 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007989
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007990 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007991 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
7992 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007993 }
7994 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02007995 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
7996 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007997 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007998 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007999
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008001 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008002 return NULL;
8003}
8004
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005/* Charmap encoding: the lookup table */
8006
Alexander Belopolsky40018472011-02-26 01:02:56 +00008007struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008008 PyObject_HEAD
8009 unsigned char level1[32];
8010 int count2, count3;
8011 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008012};
8013
8014static PyObject*
8015encoding_map_size(PyObject *obj, PyObject* args)
8016{
8017 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008018 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008019 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020}
8021
8022static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008023 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 PyDoc_STR("Return the size (in bytes) of this object") },
8025 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008026};
8027
8028static void
8029encoding_map_dealloc(PyObject* o)
8030{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008031 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008032}
8033
8034static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008035 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 "EncodingMap", /*tp_name*/
8037 sizeof(struct encoding_map), /*tp_basicsize*/
8038 0, /*tp_itemsize*/
8039 /* methods */
8040 encoding_map_dealloc, /*tp_dealloc*/
8041 0, /*tp_print*/
8042 0, /*tp_getattr*/
8043 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008044 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008045 0, /*tp_repr*/
8046 0, /*tp_as_number*/
8047 0, /*tp_as_sequence*/
8048 0, /*tp_as_mapping*/
8049 0, /*tp_hash*/
8050 0, /*tp_call*/
8051 0, /*tp_str*/
8052 0, /*tp_getattro*/
8053 0, /*tp_setattro*/
8054 0, /*tp_as_buffer*/
8055 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8056 0, /*tp_doc*/
8057 0, /*tp_traverse*/
8058 0, /*tp_clear*/
8059 0, /*tp_richcompare*/
8060 0, /*tp_weaklistoffset*/
8061 0, /*tp_iter*/
8062 0, /*tp_iternext*/
8063 encoding_map_methods, /*tp_methods*/
8064 0, /*tp_members*/
8065 0, /*tp_getset*/
8066 0, /*tp_base*/
8067 0, /*tp_dict*/
8068 0, /*tp_descr_get*/
8069 0, /*tp_descr_set*/
8070 0, /*tp_dictoffset*/
8071 0, /*tp_init*/
8072 0, /*tp_alloc*/
8073 0, /*tp_new*/
8074 0, /*tp_free*/
8075 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008076};
8077
8078PyObject*
8079PyUnicode_BuildEncodingMap(PyObject* string)
8080{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008081 PyObject *result;
8082 struct encoding_map *mresult;
8083 int i;
8084 int need_dict = 0;
8085 unsigned char level1[32];
8086 unsigned char level2[512];
8087 unsigned char *mlevel1, *mlevel2, *mlevel3;
8088 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008089 int kind;
8090 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008091 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008092 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008093
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008094 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008095 PyErr_BadArgument();
8096 return NULL;
8097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008098 kind = PyUnicode_KIND(string);
8099 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008100 length = PyUnicode_GET_LENGTH(string);
8101 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102 memset(level1, 0xFF, sizeof level1);
8103 memset(level2, 0xFF, sizeof level2);
8104
8105 /* If there isn't a one-to-one mapping of NULL to \0,
8106 or if there are non-BMP characters, we need to use
8107 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008108 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008109 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008110 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008112 ch = PyUnicode_READ(kind, data, i);
8113 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008114 need_dict = 1;
8115 break;
8116 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008117 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008118 /* unmapped character */
8119 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008120 l1 = ch >> 11;
8121 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008122 if (level1[l1] == 0xFF)
8123 level1[l1] = count2++;
8124 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008125 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008126 }
8127
8128 if (count2 >= 0xFF || count3 >= 0xFF)
8129 need_dict = 1;
8130
8131 if (need_dict) {
8132 PyObject *result = PyDict_New();
8133 PyObject *key, *value;
8134 if (!result)
8135 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008136 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008137 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008138 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008139 if (!key || !value)
8140 goto failed1;
8141 if (PyDict_SetItem(result, key, value) == -1)
8142 goto failed1;
8143 Py_DECREF(key);
8144 Py_DECREF(value);
8145 }
8146 return result;
8147 failed1:
8148 Py_XDECREF(key);
8149 Py_XDECREF(value);
8150 Py_DECREF(result);
8151 return NULL;
8152 }
8153
8154 /* Create a three-level trie */
8155 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8156 16*count2 + 128*count3 - 1);
8157 if (!result)
8158 return PyErr_NoMemory();
8159 PyObject_Init(result, &EncodingMapType);
8160 mresult = (struct encoding_map*)result;
8161 mresult->count2 = count2;
8162 mresult->count3 = count3;
8163 mlevel1 = mresult->level1;
8164 mlevel2 = mresult->level23;
8165 mlevel3 = mresult->level23 + 16*count2;
8166 memcpy(mlevel1, level1, 32);
8167 memset(mlevel2, 0xFF, 16*count2);
8168 memset(mlevel3, 0, 128*count3);
8169 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008170 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008172 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8173 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008174 /* unmapped character */
8175 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008176 o1 = ch>>11;
8177 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008178 i2 = 16*mlevel1[o1] + o2;
8179 if (mlevel2[i2] == 0xFF)
8180 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008181 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008182 i3 = 128*mlevel2[i2] + o3;
8183 mlevel3[i3] = i;
8184 }
8185 return result;
8186}
8187
8188static int
Victor Stinner22168992011-11-20 17:09:18 +01008189encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190{
8191 struct encoding_map *map = (struct encoding_map*)mapping;
8192 int l1 = c>>11;
8193 int l2 = (c>>7) & 0xF;
8194 int l3 = c & 0x7F;
8195 int i;
8196
Victor Stinner22168992011-11-20 17:09:18 +01008197 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008199 if (c == 0)
8200 return 0;
8201 /* level 1*/
8202 i = map->level1[l1];
8203 if (i == 0xFF) {
8204 return -1;
8205 }
8206 /* level 2*/
8207 i = map->level23[16*i+l2];
8208 if (i == 0xFF) {
8209 return -1;
8210 }
8211 /* level 3 */
8212 i = map->level23[16*map->count2 + 128*i + l3];
8213 if (i == 0) {
8214 return -1;
8215 }
8216 return i;
8217}
8218
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008219/* Lookup the character ch in the mapping. If the character
8220 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008221 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008222static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008223charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008224{
Christian Heimes217cfd12007-12-02 14:31:20 +00008225 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008226 PyObject *x;
8227
8228 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008230 x = PyObject_GetItem(mapping, w);
8231 Py_DECREF(w);
8232 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8234 /* No mapping found means: mapping is undefined. */
8235 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008236 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008237 } else
8238 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008239 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008240 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008242 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008243 long value = PyLong_AS_LONG(x);
8244 if (value < 0 || value > 255) {
8245 PyErr_SetString(PyExc_TypeError,
8246 "character mapping must be in range(256)");
8247 Py_DECREF(x);
8248 return NULL;
8249 }
8250 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008251 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008252 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008253 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008254 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 /* wrong return value */
8256 PyErr_Format(PyExc_TypeError,
8257 "character mapping must return integer, bytes or None, not %.400s",
8258 x->ob_type->tp_name);
8259 Py_DECREF(x);
8260 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008261 }
8262}
8263
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008264static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008265charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008266{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008267 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8268 /* exponentially overallocate to minimize reallocations */
8269 if (requiredsize < 2*outsize)
8270 requiredsize = 2*outsize;
8271 if (_PyBytes_Resize(outobj, requiredsize))
8272 return -1;
8273 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008274}
8275
Benjamin Peterson14339b62009-01-31 16:36:08 +00008276typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008277 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008278} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008279/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008280 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281 space is available. Return a new reference to the object that
8282 was put in the output buffer, or Py_None, if the mapping was undefined
8283 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008284 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008285static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008286charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008287 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008288{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008289 PyObject *rep;
8290 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008291 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292
Christian Heimes90aa7642007-12-19 02:45:37 +00008293 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008294 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008295 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008296 if (res == -1)
8297 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 if (outsize<requiredsize)
8299 if (charmapencode_resize(outobj, outpos, requiredsize))
8300 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008301 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008302 outstart[(*outpos)++] = (char)res;
8303 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008304 }
8305
8306 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008308 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008309 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 Py_DECREF(rep);
8311 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008312 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008313 if (PyLong_Check(rep)) {
8314 Py_ssize_t requiredsize = *outpos+1;
8315 if (outsize<requiredsize)
8316 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8317 Py_DECREF(rep);
8318 return enc_EXCEPTION;
8319 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008320 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008322 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 else {
8324 const char *repchars = PyBytes_AS_STRING(rep);
8325 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8326 Py_ssize_t requiredsize = *outpos+repsize;
8327 if (outsize<requiredsize)
8328 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8329 Py_DECREF(rep);
8330 return enc_EXCEPTION;
8331 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008332 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008333 memcpy(outstart + *outpos, repchars, repsize);
8334 *outpos += repsize;
8335 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008336 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008337 Py_DECREF(rep);
8338 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008339}
8340
8341/* handle an error in PyUnicode_EncodeCharmap
8342 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008343static int
8344charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008345 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008347 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008348 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349{
8350 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008351 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008352 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008353 enum PyUnicode_Kind kind;
8354 void *data;
8355 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008357 Py_ssize_t collstartpos = *inpos;
8358 Py_ssize_t collendpos = *inpos+1;
8359 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008360 const char *encoding = "charmap";
8361 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008362 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008363 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008364 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365
Benjamin Petersonbac79492012-01-14 13:34:47 -05008366 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008367 return -1;
8368 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369 /* find all unencodable characters */
8370 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008371 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008372 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008373 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008374 val = encoding_map_lookup(ch, mapping);
8375 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 break;
8377 ++collendpos;
8378 continue;
8379 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008380
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008381 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8382 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008383 if (rep==NULL)
8384 return -1;
8385 else if (rep!=Py_None) {
8386 Py_DECREF(rep);
8387 break;
8388 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008389 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 }
8392 /* cache callback name lookup
8393 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008394 if (*error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02008395 *error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02008396
8397 switch (*error_handler) {
8398 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008399 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008400 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008401
8402 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008403 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 x = charmapencode_output('?', mapping, res, respos);
8405 if (x==enc_EXCEPTION) {
8406 return -1;
8407 }
8408 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008409 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 return -1;
8411 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008412 }
8413 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008414 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008415 *inpos = collendpos;
8416 break;
Victor Stinner50149202015-09-22 00:26:54 +02008417
8418 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008419 /* generate replacement (temporarily (mis)uses p) */
8420 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 char buffer[2+29+1+1];
8422 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008423 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008424 for (cp = buffer; *cp; ++cp) {
8425 x = charmapencode_output(*cp, mapping, res, respos);
8426 if (x==enc_EXCEPTION)
8427 return -1;
8428 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008429 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 return -1;
8431 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008432 }
8433 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008434 *inpos = collendpos;
8435 break;
Victor Stinner50149202015-09-22 00:26:54 +02008436
Benjamin Peterson14339b62009-01-31 16:36:08 +00008437 default:
Victor Stinner50149202015-09-22 00:26:54 +02008438 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008439 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008440 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008441 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008443 if (PyBytes_Check(repunicode)) {
8444 /* Directly copy bytes result to output. */
8445 Py_ssize_t outsize = PyBytes_Size(*res);
8446 Py_ssize_t requiredsize;
8447 repsize = PyBytes_Size(repunicode);
8448 requiredsize = *respos + repsize;
8449 if (requiredsize > outsize)
8450 /* Make room for all additional bytes. */
8451 if (charmapencode_resize(res, respos, requiredsize)) {
8452 Py_DECREF(repunicode);
8453 return -1;
8454 }
8455 memcpy(PyBytes_AsString(*res) + *respos,
8456 PyBytes_AsString(repunicode), repsize);
8457 *respos += repsize;
8458 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008459 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008460 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008461 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008462 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008463 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008464 Py_DECREF(repunicode);
8465 return -1;
8466 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008467 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008468 data = PyUnicode_DATA(repunicode);
8469 kind = PyUnicode_KIND(repunicode);
8470 for (index = 0; index < repsize; index++) {
8471 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8472 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008474 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 return -1;
8476 }
8477 else if (x==enc_FAILED) {
8478 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008479 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 return -1;
8481 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008482 }
8483 *inpos = newpos;
8484 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008485 }
8486 return 0;
8487}
8488
Alexander Belopolsky40018472011-02-26 01:02:56 +00008489PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008490_PyUnicode_EncodeCharmap(PyObject *unicode,
8491 PyObject *mapping,
8492 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008493{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008494 /* output object */
8495 PyObject *res = NULL;
8496 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008497 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008498 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008499 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008500 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008501 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008503 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008504 void *data;
8505 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008506
Benjamin Petersonbac79492012-01-14 13:34:47 -05008507 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008508 return NULL;
8509 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008510 data = PyUnicode_DATA(unicode);
8511 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008512
Guido van Rossumd57fd912000-03-10 22:53:23 +00008513 /* Default to Latin-1 */
8514 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008515 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008516
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008517 /* allocate enough for a simple encoding without
8518 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008519 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008520 if (res == NULL)
8521 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008522 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008524
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008526 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008527 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008528 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 if (x==enc_EXCEPTION) /* error */
8530 goto onError;
8531 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008532 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008533 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008534 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 &res, &respos)) {
8536 goto onError;
8537 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008538 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 else
8540 /* done with this character => adjust input position */
8541 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008542 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008543
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008544 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008545 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008546 if (_PyBytes_Resize(&res, respos) < 0)
8547 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008548
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008549 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008550 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551 return res;
8552
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008554 Py_XDECREF(res);
8555 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008556 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008557 return NULL;
8558}
8559
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008560/* Deprecated */
8561PyObject *
8562PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8563 Py_ssize_t size,
8564 PyObject *mapping,
8565 const char *errors)
8566{
8567 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008568 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008569 if (unicode == NULL)
8570 return NULL;
8571 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8572 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008573 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008574}
8575
Alexander Belopolsky40018472011-02-26 01:02:56 +00008576PyObject *
8577PyUnicode_AsCharmapString(PyObject *unicode,
8578 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008579{
8580 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 PyErr_BadArgument();
8582 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008583 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008584 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008585}
8586
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008588static void
8589make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008591 Py_ssize_t startpos, Py_ssize_t endpos,
8592 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008593{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 *exceptionObject = _PyUnicodeTranslateError_Create(
8596 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008597 }
8598 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8600 goto onError;
8601 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8602 goto onError;
8603 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8604 goto onError;
8605 return;
8606 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008607 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008608 }
8609}
8610
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008611/* error handling callback helper:
8612 build arguments, call the callback and check the arguments,
8613 put the result into newpos and return the replacement string, which
8614 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008615static PyObject *
8616unicode_translate_call_errorhandler(const char *errors,
8617 PyObject **errorHandler,
8618 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008620 Py_ssize_t startpos, Py_ssize_t endpos,
8621 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008622{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008623 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008625 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008626 PyObject *restuple;
8627 PyObject *resunicode;
8628
8629 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008631 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008633 }
8634
8635 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008637 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008638 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008639
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008640 restuple = PyObject_CallFunctionObjArgs(
8641 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008642 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008645 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 Py_DECREF(restuple);
8647 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008648 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008649 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 &resunicode, &i_newpos)) {
8651 Py_DECREF(restuple);
8652 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008653 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008654 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008656 else
8657 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008658 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008659 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008660 Py_DECREF(restuple);
8661 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008662 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008663 Py_INCREF(resunicode);
8664 Py_DECREF(restuple);
8665 return resunicode;
8666}
8667
8668/* Lookup the character ch in the mapping and put the result in result,
8669 which must be decrefed by the caller.
8670 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008671static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008673{
Christian Heimes217cfd12007-12-02 14:31:20 +00008674 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675 PyObject *x;
8676
8677 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008679 x = PyObject_GetItem(mapping, w);
8680 Py_DECREF(w);
8681 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8683 /* No mapping found means: use 1:1 mapping. */
8684 PyErr_Clear();
8685 *result = NULL;
8686 return 0;
8687 } else
8688 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008689 }
8690 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 *result = x;
8692 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008693 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008694 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008696 if (value < 0 || value > MAX_UNICODE) {
8697 PyErr_Format(PyExc_ValueError,
8698 "character mapping must be in range(0x%x)",
8699 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008700 Py_DECREF(x);
8701 return -1;
8702 }
8703 *result = x;
8704 return 0;
8705 }
8706 else if (PyUnicode_Check(x)) {
8707 *result = x;
8708 return 0;
8709 }
8710 else {
8711 /* wrong return value */
8712 PyErr_SetString(PyExc_TypeError,
8713 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008714 Py_DECREF(x);
8715 return -1;
8716 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008717}
Victor Stinner1194ea02014-04-04 19:37:40 +02008718
8719/* lookup the character, write the result into the writer.
8720 Return 1 if the result was written into the writer, return 0 if the mapping
8721 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008722static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008723charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8724 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008725{
Victor Stinner1194ea02014-04-04 19:37:40 +02008726 PyObject *item;
8727
8728 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008729 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008730
8731 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008732 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008733 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008735 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008736 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008737 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008738
8739 if (item == Py_None) {
8740 Py_DECREF(item);
8741 return 0;
8742 }
8743
8744 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008745 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8746 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8747 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008748 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8749 Py_DECREF(item);
8750 return -1;
8751 }
8752 Py_DECREF(item);
8753 return 1;
8754 }
8755
8756 if (!PyUnicode_Check(item)) {
8757 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008758 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008759 }
8760
8761 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8762 Py_DECREF(item);
8763 return -1;
8764 }
8765
8766 Py_DECREF(item);
8767 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008768}
8769
Victor Stinner89a76ab2014-04-05 11:44:04 +02008770static int
8771unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8772 Py_UCS1 *translate)
8773{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008774 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008775 int ret = 0;
8776
Victor Stinner89a76ab2014-04-05 11:44:04 +02008777 if (charmaptranslate_lookup(ch, mapping, &item)) {
8778 return -1;
8779 }
8780
8781 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008782 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008783 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008784 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008785 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008786 /* not found => default to 1:1 mapping */
8787 translate[ch] = ch;
8788 return 1;
8789 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008790 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008791 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008792 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8793 used it */
8794 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008795 /* invalid character or character outside ASCII:
8796 skip the fast translate */
8797 goto exit;
8798 }
8799 translate[ch] = (Py_UCS1)replace;
8800 }
8801 else if (PyUnicode_Check(item)) {
8802 Py_UCS4 replace;
8803
8804 if (PyUnicode_READY(item) == -1) {
8805 Py_DECREF(item);
8806 return -1;
8807 }
8808 if (PyUnicode_GET_LENGTH(item) != 1)
8809 goto exit;
8810
8811 replace = PyUnicode_READ_CHAR(item, 0);
8812 if (replace > 127)
8813 goto exit;
8814 translate[ch] = (Py_UCS1)replace;
8815 }
8816 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008817 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008818 goto exit;
8819 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008820 ret = 1;
8821
Benjamin Peterson1365de72014-04-07 20:15:41 -04008822 exit:
8823 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008824 return ret;
8825}
8826
8827/* Fast path for ascii => ascii translation. Return 1 if the whole string
8828 was translated into writer, return 0 if the input string was partially
8829 translated into writer, raise an exception and return -1 on error. */
8830static int
8831unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008832 _PyUnicodeWriter *writer, int ignore,
8833 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008834{
Victor Stinner872b2912014-04-05 14:27:07 +02008835 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008836 Py_ssize_t len;
8837 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008838 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008839
Victor Stinner89a76ab2014-04-05 11:44:04 +02008840 len = PyUnicode_GET_LENGTH(input);
8841
Victor Stinner872b2912014-04-05 14:27:07 +02008842 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008843
8844 in = PyUnicode_1BYTE_DATA(input);
8845 end = in + len;
8846
8847 assert(PyUnicode_IS_ASCII(writer->buffer));
8848 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8849 out = PyUnicode_1BYTE_DATA(writer->buffer);
8850
Victor Stinner872b2912014-04-05 14:27:07 +02008851 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008852 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008853 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008854 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008855 int translate = unicode_fast_translate_lookup(mapping, ch,
8856 ascii_table);
8857 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008858 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008859 if (translate == 0)
8860 goto exit;
8861 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008862 }
Victor Stinner872b2912014-04-05 14:27:07 +02008863 if (ch2 == 0xfe) {
8864 if (ignore)
8865 continue;
8866 goto exit;
8867 }
8868 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008869 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008870 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008871 }
Victor Stinner872b2912014-04-05 14:27:07 +02008872 res = 1;
8873
8874exit:
8875 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008876 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008877 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008878}
8879
Victor Stinner3222da22015-10-01 22:07:32 +02008880static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008881_PyUnicode_TranslateCharmap(PyObject *input,
8882 PyObject *mapping,
8883 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008884{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008885 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008886 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008887 Py_ssize_t size, i;
8888 int kind;
8889 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008890 _PyUnicodeWriter writer;
8891 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008892 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008893 PyObject *errorHandler = NULL;
8894 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008895 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008896 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008897
Guido van Rossumd57fd912000-03-10 22:53:23 +00008898 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008899 PyErr_BadArgument();
8900 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008901 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008903 if (PyUnicode_READY(input) == -1)
8904 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008905 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008906 kind = PyUnicode_KIND(input);
8907 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008908
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008909 if (size == 0)
8910 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008911
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008912 /* allocate enough for a simple 1:1 translation without
8913 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008914 _PyUnicodeWriter_Init(&writer);
8915 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008916 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008917
Victor Stinner872b2912014-04-05 14:27:07 +02008918 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8919
Victor Stinner33798672016-03-01 21:59:58 +01008920 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008921 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008922 if (PyUnicode_IS_ASCII(input)) {
8923 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
8924 if (res < 0) {
8925 _PyUnicodeWriter_Dealloc(&writer);
8926 return NULL;
8927 }
8928 if (res == 1)
8929 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008930 }
Victor Stinner33798672016-03-01 21:59:58 +01008931 else {
8932 i = 0;
8933 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008934
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008935 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008936 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008937 int translate;
8938 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8939 Py_ssize_t newpos;
8940 /* startpos for collecting untranslatable chars */
8941 Py_ssize_t collstart;
8942 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02008943 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008944
Victor Stinner1194ea02014-04-04 19:37:40 +02008945 ch = PyUnicode_READ(kind, data, i);
8946 translate = charmaptranslate_output(ch, mapping, &writer);
8947 if (translate < 0)
8948 goto onError;
8949
8950 if (translate != 0) {
8951 /* it worked => adjust input pointer */
8952 ++i;
8953 continue;
8954 }
8955
8956 /* untranslatable character */
8957 collstart = i;
8958 collend = i+1;
8959
8960 /* find all untranslatable characters */
8961 while (collend < size) {
8962 PyObject *x;
8963 ch = PyUnicode_READ(kind, data, collend);
8964 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00008965 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02008966 Py_XDECREF(x);
8967 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008968 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02008969 ++collend;
8970 }
8971
8972 if (ignore) {
8973 i = collend;
8974 }
8975 else {
8976 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
8977 reason, input, &exc,
8978 collstart, collend, &newpos);
8979 if (repunicode == NULL)
8980 goto onError;
8981 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008982 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02008983 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008984 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008985 Py_DECREF(repunicode);
8986 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008987 }
8988 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008989 Py_XDECREF(exc);
8990 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02008991 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008992
Benjamin Peterson29060642009-01-31 22:14:21 +00008993 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02008994 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008995 Py_XDECREF(exc);
8996 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008997 return NULL;
8998}
8999
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009000/* Deprecated. Use PyUnicode_Translate instead. */
9001PyObject *
9002PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9003 Py_ssize_t size,
9004 PyObject *mapping,
9005 const char *errors)
9006{
Christian Heimes5f520f42012-09-11 14:03:25 +02009007 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009008 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009009 if (!unicode)
9010 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009011 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9012 Py_DECREF(unicode);
9013 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009014}
9015
Alexander Belopolsky40018472011-02-26 01:02:56 +00009016PyObject *
9017PyUnicode_Translate(PyObject *str,
9018 PyObject *mapping,
9019 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009020{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009021 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009022 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009023 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009024}
Tim Petersced69f82003-09-16 20:30:58 +00009025
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009026PyObject *
9027_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9028{
9029 if (!PyUnicode_Check(unicode)) {
9030 PyErr_BadInternalCall();
9031 return NULL;
9032 }
9033 if (PyUnicode_READY(unicode) == -1)
9034 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009035 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009036 /* If the string is already ASCII, just return the same string */
9037 Py_INCREF(unicode);
9038 return unicode;
9039 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009040
9041 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9042 PyObject *result = PyUnicode_New(len, 127);
9043 if (result == NULL) {
9044 return NULL;
9045 }
9046
9047 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9048 int kind = PyUnicode_KIND(unicode);
9049 const void *data = PyUnicode_DATA(unicode);
9050 Py_ssize_t i;
9051 for (i = 0; i < len; ++i) {
9052 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9053 if (ch < 127) {
9054 out[i] = ch;
9055 }
9056 else if (Py_UNICODE_ISSPACE(ch)) {
9057 out[i] = ' ';
9058 }
9059 else {
9060 int decimal = Py_UNICODE_TODECIMAL(ch);
9061 if (decimal < 0) {
9062 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009063 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009064 _PyUnicode_LENGTH(result) = i + 1;
9065 break;
9066 }
9067 out[i] = '0' + decimal;
9068 }
9069 }
9070
INADA Naoki16dfca42018-07-14 12:06:43 +09009071 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009072 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009073}
9074
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009075PyObject *
9076PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9077 Py_ssize_t length)
9078{
Victor Stinnerf0124502011-11-21 23:12:56 +01009079 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009080 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009081 Py_UCS4 maxchar;
9082 enum PyUnicode_Kind kind;
9083 void *data;
9084
Victor Stinner99d7ad02012-02-22 13:37:39 +01009085 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009086 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009087 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009088 if (ch > 127) {
9089 int decimal = Py_UNICODE_TODECIMAL(ch);
9090 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009091 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009092 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009093 }
9094 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009095
9096 /* Copy to a new string */
9097 decimal = PyUnicode_New(length, maxchar);
9098 if (decimal == NULL)
9099 return decimal;
9100 kind = PyUnicode_KIND(decimal);
9101 data = PyUnicode_DATA(decimal);
9102 /* Iterate over code points */
9103 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009104 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009105 if (ch > 127) {
9106 int decimal = Py_UNICODE_TODECIMAL(ch);
9107 if (decimal >= 0)
9108 ch = '0' + decimal;
9109 }
9110 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009112 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009113}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009114/* --- Decimal Encoder ---------------------------------------------------- */
9115
Alexander Belopolsky40018472011-02-26 01:02:56 +00009116int
9117PyUnicode_EncodeDecimal(Py_UNICODE *s,
9118 Py_ssize_t length,
9119 char *output,
9120 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009121{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009122 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009123 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009124 enum PyUnicode_Kind kind;
9125 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009126
9127 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009128 PyErr_BadArgument();
9129 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009130 }
9131
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009132 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009133 if (unicode == NULL)
9134 return -1;
9135
Victor Stinner42bf7752011-11-21 22:52:58 +01009136 kind = PyUnicode_KIND(unicode);
9137 data = PyUnicode_DATA(unicode);
9138
Victor Stinnerb84d7232011-11-22 01:50:07 +01009139 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009140 PyObject *exc;
9141 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009143 Py_ssize_t startpos;
9144
9145 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009146
Benjamin Peterson29060642009-01-31 22:14:21 +00009147 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009148 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009149 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009150 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009151 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009152 decimal = Py_UNICODE_TODECIMAL(ch);
9153 if (decimal >= 0) {
9154 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009155 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009156 continue;
9157 }
9158 if (0 < ch && ch < 256) {
9159 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009160 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009161 continue;
9162 }
Victor Stinner6345be92011-11-25 20:09:01 +01009163
Victor Stinner42bf7752011-11-21 22:52:58 +01009164 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009165 exc = NULL;
9166 raise_encode_exception(&exc, "decimal", unicode,
9167 startpos, startpos+1,
9168 "invalid decimal Unicode string");
9169 Py_XDECREF(exc);
9170 Py_DECREF(unicode);
9171 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009172 }
9173 /* 0-terminate the output string */
9174 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009175 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009176 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009177}
9178
Guido van Rossumd57fd912000-03-10 22:53:23 +00009179/* --- Helpers ------------------------------------------------------------ */
9180
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009181/* helper macro to fixup start/end slice values */
9182#define ADJUST_INDICES(start, end, len) \
9183 if (end > len) \
9184 end = len; \
9185 else if (end < 0) { \
9186 end += len; \
9187 if (end < 0) \
9188 end = 0; \
9189 } \
9190 if (start < 0) { \
9191 start += len; \
9192 if (start < 0) \
9193 start = 0; \
9194 }
9195
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009196static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009197any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009199 Py_ssize_t end,
9200 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009201{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009202 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 void *buf1, *buf2;
9204 Py_ssize_t len1, len2, result;
9205
9206 kind1 = PyUnicode_KIND(s1);
9207 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009208 if (kind1 < kind2)
9209 return -1;
9210
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009211 len1 = PyUnicode_GET_LENGTH(s1);
9212 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009213 ADJUST_INDICES(start, end, len1);
9214 if (end - start < len2)
9215 return -1;
9216
9217 buf1 = PyUnicode_DATA(s1);
9218 buf2 = PyUnicode_DATA(s2);
9219 if (len2 == 1) {
9220 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9221 result = findchar((const char *)buf1 + kind1*start,
9222 kind1, end - start, ch, direction);
9223 if (result == -1)
9224 return -1;
9225 else
9226 return start + result;
9227 }
9228
9229 if (kind2 != kind1) {
9230 buf2 = _PyUnicode_AsKind(s2, kind1);
9231 if (!buf2)
9232 return -2;
9233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234
Victor Stinner794d5672011-10-10 03:21:36 +02009235 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009236 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009237 case PyUnicode_1BYTE_KIND:
9238 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9239 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9240 else
9241 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9242 break;
9243 case PyUnicode_2BYTE_KIND:
9244 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9245 break;
9246 case PyUnicode_4BYTE_KIND:
9247 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9248 break;
9249 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009250 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009251 }
9252 }
9253 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009254 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009255 case PyUnicode_1BYTE_KIND:
9256 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9257 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9258 else
9259 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9260 break;
9261 case PyUnicode_2BYTE_KIND:
9262 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9263 break;
9264 case PyUnicode_4BYTE_KIND:
9265 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9266 break;
9267 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009268 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009269 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270 }
9271
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009272 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009273 PyMem_Free(buf2);
9274
9275 return result;
9276}
9277
Victor Stinner59423e32018-11-26 13:40:01 +01009278/* _PyUnicode_InsertThousandsGrouping() helper functions */
9279#include "stringlib/localeutil.h"
9280
9281/**
9282 * InsertThousandsGrouping:
9283 * @writer: Unicode writer.
9284 * @n_buffer: Number of characters in @buffer.
9285 * @digits: Digits we're reading from. If count is non-NULL, this is unused.
9286 * @d_pos: Start of digits string.
9287 * @n_digits: The number of digits in the string, in which we want
9288 * to put the grouping chars.
9289 * @min_width: The minimum width of the digits in the output string.
9290 * Output will be zero-padded on the left to fill.
9291 * @grouping: see definition in localeconv().
9292 * @thousands_sep: see definition in localeconv().
9293 *
9294 * There are 2 modes: counting and filling. If @writer is NULL,
9295 * we are in counting mode, else filling mode.
9296 * If counting, the required buffer size is returned.
9297 * If filling, we know the buffer will be large enough, so we don't
9298 * need to pass in the buffer size.
9299 * Inserts thousand grouping characters (as defined by grouping and
9300 * thousands_sep) into @writer.
9301 *
9302 * Return value: -1 on error, number of characters otherwise.
9303 **/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009304Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009305_PyUnicode_InsertThousandsGrouping(
Victor Stinner59423e32018-11-26 13:40:01 +01009306 _PyUnicodeWriter *writer,
Victor Stinner41a863c2012-02-24 00:37:51 +01009307 Py_ssize_t n_buffer,
Victor Stinner59423e32018-11-26 13:40:01 +01009308 PyObject *digits,
9309 Py_ssize_t d_pos,
9310 Py_ssize_t n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009311 Py_ssize_t min_width,
Victor Stinner59423e32018-11-26 13:40:01 +01009312 const char *grouping,
9313 PyObject *thousands_sep,
Victor Stinner41a863c2012-02-24 00:37:51 +01009314 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009315{
Xtreak3f7983a2019-01-07 20:39:14 +05309316 min_width = Py_MAX(0, min_width);
Victor Stinner59423e32018-11-26 13:40:01 +01009317 if (writer) {
9318 assert(digits != NULL);
9319 assert(maxchar == NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009320 }
9321 else {
Victor Stinner59423e32018-11-26 13:40:01 +01009322 assert(digits == NULL);
9323 assert(maxchar != NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009324 }
Victor Stinner59423e32018-11-26 13:40:01 +01009325 assert(0 <= d_pos);
9326 assert(0 <= n_digits);
Victor Stinner59423e32018-11-26 13:40:01 +01009327 assert(grouping != NULL);
9328
9329 if (digits != NULL) {
9330 if (PyUnicode_READY(digits) == -1) {
9331 return -1;
Victor Stinner90f50d42012-02-24 01:44:47 +01009332 }
Victor Stinner59423e32018-11-26 13:40:01 +01009333 }
9334 if (PyUnicode_READY(thousands_sep) == -1) {
9335 return -1;
Victor Stinner41a863c2012-02-24 00:37:51 +01009336 }
9337
Victor Stinner59423e32018-11-26 13:40:01 +01009338 Py_ssize_t count = 0;
9339 Py_ssize_t n_zeros;
9340 int loop_broken = 0;
9341 int use_separator = 0; /* First time through, don't append the
9342 separator. They only go between
9343 groups. */
9344 Py_ssize_t buffer_pos;
9345 Py_ssize_t digits_pos;
9346 Py_ssize_t len;
9347 Py_ssize_t n_chars;
9348 Py_ssize_t remaining = n_digits; /* Number of chars remaining to
9349 be looked at */
9350 /* A generator that returns all of the grouping widths, until it
9351 returns 0. */
9352 GroupGenerator groupgen;
9353 GroupGenerator_init(&groupgen, grouping);
9354 const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9355
9356 /* if digits are not grouped, thousands separator
9357 should be an empty string */
9358 assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
9359
9360 digits_pos = d_pos + n_digits;
9361 if (writer) {
9362 buffer_pos = writer->pos + n_buffer;
9363 assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
9364 assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009365 }
Victor Stinner59423e32018-11-26 13:40:01 +01009366 else {
9367 buffer_pos = n_buffer;
Victor Stinner90f50d42012-02-24 01:44:47 +01009368 }
Victor Stinner59423e32018-11-26 13:40:01 +01009369
9370 if (!writer) {
Victor Stinner41a863c2012-02-24 00:37:51 +01009371 *maxchar = 127;
Victor Stinner41a863c2012-02-24 00:37:51 +01009372 }
Victor Stinner59423e32018-11-26 13:40:01 +01009373
9374 while ((len = GroupGenerator_next(&groupgen)) > 0) {
9375 len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
9376 n_zeros = Py_MAX(0, len - remaining);
9377 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9378
9379 /* Use n_zero zero's and n_chars chars */
9380
9381 /* Count only, don't do anything. */
9382 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9383
9384 /* Copy into the writer. */
9385 InsertThousandsGrouping_fill(writer, &buffer_pos,
9386 digits, &digits_pos,
9387 n_chars, n_zeros,
9388 use_separator ? thousands_sep : NULL,
9389 thousands_sep_len, maxchar);
9390
9391 /* Use a separator next time. */
9392 use_separator = 1;
9393
9394 remaining -= n_chars;
9395 min_width -= len;
9396
9397 if (remaining <= 0 && min_width <= 0) {
9398 loop_broken = 1;
9399 break;
9400 }
9401 min_width -= thousands_sep_len;
9402 }
9403 if (!loop_broken) {
9404 /* We left the loop without using a break statement. */
9405
9406 len = Py_MAX(Py_MAX(remaining, min_width), 1);
9407 n_zeros = Py_MAX(0, len - remaining);
9408 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9409
9410 /* Use n_zero zero's and n_chars chars */
9411 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9412
9413 /* Copy into the writer. */
9414 InsertThousandsGrouping_fill(writer, &buffer_pos,
9415 digits, &digits_pos,
9416 n_chars, n_zeros,
9417 use_separator ? thousands_sep : NULL,
9418 thousands_sep_len, maxchar);
9419 }
9420 return count;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421}
9422
9423
Alexander Belopolsky40018472011-02-26 01:02:56 +00009424Py_ssize_t
9425PyUnicode_Count(PyObject *str,
9426 PyObject *substr,
9427 Py_ssize_t start,
9428 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009430 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009431 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009432 void *buf1 = NULL, *buf2 = NULL;
9433 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009434
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009435 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009436 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009437
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009438 kind1 = PyUnicode_KIND(str);
9439 kind2 = PyUnicode_KIND(substr);
9440 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009441 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009442
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009443 len1 = PyUnicode_GET_LENGTH(str);
9444 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009446 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009447 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009448
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009449 buf1 = PyUnicode_DATA(str);
9450 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009451 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009452 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009453 if (!buf2)
9454 goto onError;
9455 }
9456
9457 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009459 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009460 result = asciilib_count(
9461 ((Py_UCS1*)buf1) + start, end - start,
9462 buf2, len2, PY_SSIZE_T_MAX
9463 );
9464 else
9465 result = ucs1lib_count(
9466 ((Py_UCS1*)buf1) + start, end - start,
9467 buf2, len2, PY_SSIZE_T_MAX
9468 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009469 break;
9470 case PyUnicode_2BYTE_KIND:
9471 result = ucs2lib_count(
9472 ((Py_UCS2*)buf1) + start, end - start,
9473 buf2, len2, PY_SSIZE_T_MAX
9474 );
9475 break;
9476 case PyUnicode_4BYTE_KIND:
9477 result = ucs4lib_count(
9478 ((Py_UCS4*)buf1) + start, end - start,
9479 buf2, len2, PY_SSIZE_T_MAX
9480 );
9481 break;
9482 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009483 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009484 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009485
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009486 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487 PyMem_Free(buf2);
9488
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009491 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 PyMem_Free(buf2);
9493 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009494}
9495
Alexander Belopolsky40018472011-02-26 01:02:56 +00009496Py_ssize_t
9497PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009498 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009499 Py_ssize_t start,
9500 Py_ssize_t end,
9501 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009502{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009503 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009504 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009505
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009506 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009507}
9508
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009509Py_ssize_t
9510PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9511 Py_ssize_t start, Py_ssize_t end,
9512 int direction)
9513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009515 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 if (PyUnicode_READY(str) == -1)
9517 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009518 len = PyUnicode_GET_LENGTH(str);
9519 ADJUST_INDICES(start, end, len);
9520 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009521 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009523 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9524 kind, end-start, ch, direction);
9525 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009527 else
9528 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529}
9530
Alexander Belopolsky40018472011-02-26 01:02:56 +00009531static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009532tailmatch(PyObject *self,
9533 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009534 Py_ssize_t start,
9535 Py_ssize_t end,
9536 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009538 int kind_self;
9539 int kind_sub;
9540 void *data_self;
9541 void *data_sub;
9542 Py_ssize_t offset;
9543 Py_ssize_t i;
9544 Py_ssize_t end_sub;
9545
9546 if (PyUnicode_READY(self) == -1 ||
9547 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009548 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009550 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9551 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009552 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009553 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009554
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009555 if (PyUnicode_GET_LENGTH(substring) == 0)
9556 return 1;
9557
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558 kind_self = PyUnicode_KIND(self);
9559 data_self = PyUnicode_DATA(self);
9560 kind_sub = PyUnicode_KIND(substring);
9561 data_sub = PyUnicode_DATA(substring);
9562 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9563
9564 if (direction > 0)
9565 offset = end;
9566 else
9567 offset = start;
9568
9569 if (PyUnicode_READ(kind_self, data_self, offset) ==
9570 PyUnicode_READ(kind_sub, data_sub, 0) &&
9571 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9572 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9573 /* If both are of the same kind, memcmp is sufficient */
9574 if (kind_self == kind_sub) {
9575 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009576 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009577 data_sub,
9578 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009579 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009581 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582 else {
9583 /* We do not need to compare 0 and len(substring)-1 because
9584 the if statement above ensured already that they are equal
9585 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009586 for (i = 1; i < end_sub; ++i) {
9587 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9588 PyUnicode_READ(kind_sub, data_sub, i))
9589 return 0;
9590 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009591 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593 }
9594
9595 return 0;
9596}
9597
Alexander Belopolsky40018472011-02-26 01:02:56 +00009598Py_ssize_t
9599PyUnicode_Tailmatch(PyObject *str,
9600 PyObject *substr,
9601 Py_ssize_t start,
9602 Py_ssize_t end,
9603 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009604{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009605 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009606 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009607
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009608 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009609}
9610
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009611static PyObject *
9612ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009614 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9615 char *resdata, *data = PyUnicode_DATA(self);
9616 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009617
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009618 res = PyUnicode_New(len, 127);
9619 if (res == NULL)
9620 return NULL;
9621 resdata = PyUnicode_DATA(res);
9622 if (lower)
9623 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009625 _Py_bytes_upper(resdata, data, len);
9626 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009627}
9628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009629static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009630handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009632 Py_ssize_t j;
9633 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009634 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009635 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009636
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009637 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9638
9639 where ! is a negation and \p{xxx} is a character with property xxx.
9640 */
9641 for (j = i - 1; j >= 0; j--) {
9642 c = PyUnicode_READ(kind, data, j);
9643 if (!_PyUnicode_IsCaseIgnorable(c))
9644 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009645 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009646 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9647 if (final_sigma) {
9648 for (j = i + 1; j < length; j++) {
9649 c = PyUnicode_READ(kind, data, j);
9650 if (!_PyUnicode_IsCaseIgnorable(c))
9651 break;
9652 }
9653 final_sigma = j == length || !_PyUnicode_IsCased(c);
9654 }
9655 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656}
9657
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009658static int
9659lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9660 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009661{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009662 /* Obscure special case. */
9663 if (c == 0x3A3) {
9664 mapped[0] = handle_capital_sigma(kind, data, length, i);
9665 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009666 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009667 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009668}
9669
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009670static Py_ssize_t
9671do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009672{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009673 Py_ssize_t i, k = 0;
9674 int n_res, j;
9675 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009676
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009677 c = PyUnicode_READ(kind, data, 0);
9678 n_res = _PyUnicode_ToUpperFull(c, mapped);
9679 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009680 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009681 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009683 for (i = 1; i < length; i++) {
9684 c = PyUnicode_READ(kind, data, i);
9685 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9686 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009687 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009688 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009689 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009690 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009692}
9693
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009694static Py_ssize_t
9695do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9696 Py_ssize_t i, k = 0;
9697
9698 for (i = 0; i < length; i++) {
9699 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9700 int n_res, j;
9701 if (Py_UNICODE_ISUPPER(c)) {
9702 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9703 }
9704 else if (Py_UNICODE_ISLOWER(c)) {
9705 n_res = _PyUnicode_ToUpperFull(c, mapped);
9706 }
9707 else {
9708 n_res = 1;
9709 mapped[0] = c;
9710 }
9711 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009712 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009713 res[k++] = mapped[j];
9714 }
9715 }
9716 return k;
9717}
9718
9719static Py_ssize_t
9720do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9721 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009722{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009723 Py_ssize_t i, k = 0;
9724
9725 for (i = 0; i < length; i++) {
9726 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9727 int n_res, j;
9728 if (lower)
9729 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9730 else
9731 n_res = _PyUnicode_ToUpperFull(c, mapped);
9732 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009733 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009734 res[k++] = mapped[j];
9735 }
9736 }
9737 return k;
9738}
9739
9740static Py_ssize_t
9741do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9742{
9743 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9744}
9745
9746static Py_ssize_t
9747do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9748{
9749 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9750}
9751
Benjamin Petersone51757f2012-01-12 21:10:29 -05009752static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009753do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9754{
9755 Py_ssize_t i, k = 0;
9756
9757 for (i = 0; i < length; i++) {
9758 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9759 Py_UCS4 mapped[3];
9760 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9761 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009762 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009763 res[k++] = mapped[j];
9764 }
9765 }
9766 return k;
9767}
9768
9769static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009770do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9771{
9772 Py_ssize_t i, k = 0;
9773 int previous_is_cased;
9774
9775 previous_is_cased = 0;
9776 for (i = 0; i < length; i++) {
9777 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9778 Py_UCS4 mapped[3];
9779 int n_res, j;
9780
9781 if (previous_is_cased)
9782 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9783 else
9784 n_res = _PyUnicode_ToTitleFull(c, mapped);
9785
9786 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009787 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009788 res[k++] = mapped[j];
9789 }
9790
9791 previous_is_cased = _PyUnicode_IsCased(c);
9792 }
9793 return k;
9794}
9795
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009796static PyObject *
9797case_operation(PyObject *self,
9798 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9799{
9800 PyObject *res = NULL;
9801 Py_ssize_t length, newlength = 0;
9802 int kind, outkind;
9803 void *data, *outdata;
9804 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9805
Benjamin Petersoneea48462012-01-16 14:28:50 -05009806 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009807
9808 kind = PyUnicode_KIND(self);
9809 data = PyUnicode_DATA(self);
9810 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009811 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009812 PyErr_SetString(PyExc_OverflowError, "string is too long");
9813 return NULL;
9814 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009815 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009816 if (tmp == NULL)
9817 return PyErr_NoMemory();
9818 newlength = perform(kind, data, length, tmp, &maxchar);
9819 res = PyUnicode_New(newlength, maxchar);
9820 if (res == NULL)
9821 goto leave;
9822 tmpend = tmp + newlength;
9823 outdata = PyUnicode_DATA(res);
9824 outkind = PyUnicode_KIND(res);
9825 switch (outkind) {
9826 case PyUnicode_1BYTE_KIND:
9827 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9828 break;
9829 case PyUnicode_2BYTE_KIND:
9830 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9831 break;
9832 case PyUnicode_4BYTE_KIND:
9833 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9834 break;
9835 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009836 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009837 }
9838 leave:
9839 PyMem_FREE(tmp);
9840 return res;
9841}
9842
Tim Peters8ce9f162004-08-27 01:49:32 +00009843PyObject *
9844PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009845{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009846 PyObject *res;
9847 PyObject *fseq;
9848 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009849 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009850
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009851 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009852 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009853 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009854 }
9855
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009856 /* NOTE: the following code can't call back into Python code,
9857 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009858 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009859
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009860 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009861 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009862 res = _PyUnicode_JoinArray(separator, items, seqlen);
9863 Py_DECREF(fseq);
9864 return res;
9865}
9866
9867PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009868_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009869{
9870 PyObject *res = NULL; /* the result */
9871 PyObject *sep = NULL;
9872 Py_ssize_t seplen;
9873 PyObject *item;
9874 Py_ssize_t sz, i, res_offset;
9875 Py_UCS4 maxchar;
9876 Py_UCS4 item_maxchar;
9877 int use_memcpy;
9878 unsigned char *res_data = NULL, *sep_data = NULL;
9879 PyObject *last_obj;
9880 unsigned int kind = 0;
9881
Tim Peters05eba1f2004-08-27 21:32:02 +00009882 /* If empty sequence, return u"". */
9883 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009884 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009885 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009886
Tim Peters05eba1f2004-08-27 21:32:02 +00009887 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009888 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009889 if (seqlen == 1) {
9890 if (PyUnicode_CheckExact(items[0])) {
9891 res = items[0];
9892 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009893 return res;
9894 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009895 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009896 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009897 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009898 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009899 /* Set up sep and seplen */
9900 if (separator == NULL) {
9901 /* fall back to a blank space separator */
9902 sep = PyUnicode_FromOrdinal(' ');
9903 if (!sep)
9904 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009905 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009906 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009907 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009908 else {
9909 if (!PyUnicode_Check(separator)) {
9910 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009911 "separator: expected str instance,"
9912 " %.80s found",
9913 Py_TYPE(separator)->tp_name);
Victor Stinneracf47b82011-10-06 12:32:37 +02009914 goto onError;
9915 }
9916 if (PyUnicode_READY(separator))
9917 goto onError;
9918 sep = separator;
9919 seplen = PyUnicode_GET_LENGTH(separator);
9920 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9921 /* inc refcount to keep this code path symmetric with the
9922 above case of a blank separator */
9923 Py_INCREF(sep);
9924 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009925 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009926 }
9927
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009928 /* There are at least two things to join, or else we have a subclass
9929 * of str in the sequence.
9930 * Do a pre-pass to figure out the total amount of space we'll
9931 * need (sz), and see whether all argument are strings.
9932 */
9933 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009934#ifdef Py_DEBUG
9935 use_memcpy = 0;
9936#else
9937 use_memcpy = 1;
9938#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009939 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +08009940 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009941 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009942 if (!PyUnicode_Check(item)) {
9943 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009944 "sequence item %zd: expected str instance,"
9945 " %.80s found",
9946 i, Py_TYPE(item)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +00009947 goto onError;
9948 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 if (PyUnicode_READY(item) == -1)
9950 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +08009951 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -07009953 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +08009954 if (i != 0) {
9955 add_sz += seplen;
9956 }
9957 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009958 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009959 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009960 goto onError;
9961 }
Xiang Zhangb0541f42017-01-10 10:52:00 +08009962 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +02009963 if (use_memcpy && last_obj != NULL) {
9964 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9965 use_memcpy = 0;
9966 }
9967 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009968 }
Tim Petersced69f82003-09-16 20:30:58 +00009969
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009970 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009971 if (res == NULL)
9972 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009973
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009974 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009975#ifdef Py_DEBUG
9976 use_memcpy = 0;
9977#else
9978 if (use_memcpy) {
9979 res_data = PyUnicode_1BYTE_DATA(res);
9980 kind = PyUnicode_KIND(res);
9981 if (seplen != 0)
9982 sep_data = PyUnicode_1BYTE_DATA(sep);
9983 }
9984#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +02009985 if (use_memcpy) {
9986 for (i = 0; i < seqlen; ++i) {
9987 Py_ssize_t itemlen;
9988 item = items[i];
9989
9990 /* Copy item, and maybe the separator. */
9991 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +02009992 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +02009993 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009994 kind * seplen);
9995 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009996 }
Victor Stinner4560f9c2013-04-14 18:56:46 +02009997
9998 itemlen = PyUnicode_GET_LENGTH(item);
9999 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010000 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010001 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010002 kind * itemlen);
10003 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010004 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010005 }
10006 assert(res_data == PyUnicode_1BYTE_DATA(res)
10007 + kind * PyUnicode_GET_LENGTH(res));
10008 }
10009 else {
10010 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10011 Py_ssize_t itemlen;
10012 item = items[i];
10013
10014 /* Copy item, and maybe the separator. */
10015 if (i && seplen != 0) {
10016 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10017 res_offset += seplen;
10018 }
10019
10020 itemlen = PyUnicode_GET_LENGTH(item);
10021 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010022 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010023 res_offset += itemlen;
10024 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010025 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010026 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010027 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010028
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010030 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010032
Benjamin Peterson29060642009-01-31 22:14:21 +000010033 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010035 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010036 return NULL;
10037}
10038
Victor Stinnerd3f08822012-05-29 12:57:52 +020010039void
10040_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10041 Py_UCS4 fill_char)
10042{
10043 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Victor Stinner163403a2018-11-27 12:41:17 +010010044 void *data = PyUnicode_DATA(unicode);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010045 assert(PyUnicode_IS_READY(unicode));
10046 assert(unicode_modifiable(unicode));
10047 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10048 assert(start >= 0);
10049 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner59423e32018-11-26 13:40:01 +010010050 unicode_fill(kind, data, fill_char, start, length);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010051}
10052
Victor Stinner3fe55312012-01-04 00:33:50 +010010053Py_ssize_t
10054PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10055 Py_UCS4 fill_char)
10056{
10057 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010058
10059 if (!PyUnicode_Check(unicode)) {
10060 PyErr_BadInternalCall();
10061 return -1;
10062 }
10063 if (PyUnicode_READY(unicode) == -1)
10064 return -1;
10065 if (unicode_check_modifiable(unicode))
10066 return -1;
10067
Victor Stinnerd3f08822012-05-29 12:57:52 +020010068 if (start < 0) {
10069 PyErr_SetString(PyExc_IndexError, "string index out of range");
10070 return -1;
10071 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010072 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10073 PyErr_SetString(PyExc_ValueError,
10074 "fill character is bigger than "
10075 "the string maximum character");
10076 return -1;
10077 }
10078
10079 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10080 length = Py_MIN(maxlen, length);
10081 if (length <= 0)
10082 return 0;
10083
Victor Stinnerd3f08822012-05-29 12:57:52 +020010084 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010085 return length;
10086}
10087
Victor Stinner9310abb2011-10-05 00:59:23 +020010088static PyObject *
10089pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010090 Py_ssize_t left,
10091 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010092 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 PyObject *u;
10095 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010096 int kind;
10097 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010098
10099 if (left < 0)
10100 left = 0;
10101 if (right < 0)
10102 right = 0;
10103
Victor Stinnerc4b49542011-12-11 22:44:26 +010010104 if (left == 0 && right == 0)
10105 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010106
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10108 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010109 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10110 return NULL;
10111 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010113 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010115 if (!u)
10116 return NULL;
10117
10118 kind = PyUnicode_KIND(u);
10119 data = PyUnicode_DATA(u);
10120 if (left)
Victor Stinner59423e32018-11-26 13:40:01 +010010121 unicode_fill(kind, data, fill, 0, left);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010122 if (right)
Victor Stinner59423e32018-11-26 13:40:01 +010010123 unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010124 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010125 assert(_PyUnicode_CheckConsistency(u, 1));
10126 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010127}
10128
Alexander Belopolsky40018472011-02-26 01:02:56 +000010129PyObject *
10130PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010131{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010132 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010133
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010134 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010135 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010136
Benjamin Petersonead6b532011-12-20 17:23:42 -060010137 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010139 if (PyUnicode_IS_ASCII(string))
10140 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010141 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010142 PyUnicode_GET_LENGTH(string), keepends);
10143 else
10144 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010145 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010146 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 break;
10148 case PyUnicode_2BYTE_KIND:
10149 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010150 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 PyUnicode_GET_LENGTH(string), keepends);
10152 break;
10153 case PyUnicode_4BYTE_KIND:
10154 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010155 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 PyUnicode_GET_LENGTH(string), keepends);
10157 break;
10158 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010159 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010161 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010162}
10163
Alexander Belopolsky40018472011-02-26 01:02:56 +000010164static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010165split(PyObject *self,
10166 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010167 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010168{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010169 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 void *buf1, *buf2;
10171 Py_ssize_t len1, len2;
10172 PyObject* out;
10173
Guido van Rossumd57fd912000-03-10 22:53:23 +000010174 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010175 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010176
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 if (PyUnicode_READY(self) == -1)
10178 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010179
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010180 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010181 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010183 if (PyUnicode_IS_ASCII(self))
10184 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010185 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010186 PyUnicode_GET_LENGTH(self), maxcount
10187 );
10188 else
10189 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010190 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010191 PyUnicode_GET_LENGTH(self), maxcount
10192 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 case PyUnicode_2BYTE_KIND:
10194 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010195 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010196 PyUnicode_GET_LENGTH(self), maxcount
10197 );
10198 case PyUnicode_4BYTE_KIND:
10199 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010200 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 PyUnicode_GET_LENGTH(self), maxcount
10202 );
10203 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010204 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205 }
10206
10207 if (PyUnicode_READY(substring) == -1)
10208 return NULL;
10209
10210 kind1 = PyUnicode_KIND(self);
10211 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 len1 = PyUnicode_GET_LENGTH(self);
10213 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010214 if (kind1 < kind2 || len1 < len2) {
10215 out = PyList_New(1);
10216 if (out == NULL)
10217 return NULL;
10218 Py_INCREF(self);
10219 PyList_SET_ITEM(out, 0, self);
10220 return out;
10221 }
10222 buf1 = PyUnicode_DATA(self);
10223 buf2 = PyUnicode_DATA(substring);
10224 if (kind2 != kind1) {
10225 buf2 = _PyUnicode_AsKind(substring, kind1);
10226 if (!buf2)
10227 return NULL;
10228 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010230 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010232 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10233 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010234 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010235 else
10236 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010237 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 break;
10239 case PyUnicode_2BYTE_KIND:
10240 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010241 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 break;
10243 case PyUnicode_4BYTE_KIND:
10244 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010245 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 break;
10247 default:
10248 out = NULL;
10249 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010250 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 PyMem_Free(buf2);
10252 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010253}
10254
Alexander Belopolsky40018472011-02-26 01:02:56 +000010255static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010256rsplit(PyObject *self,
10257 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010258 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010259{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010260 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 void *buf1, *buf2;
10262 Py_ssize_t len1, len2;
10263 PyObject* out;
10264
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010265 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010266 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 if (PyUnicode_READY(self) == -1)
10269 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010272 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274 if (PyUnicode_IS_ASCII(self))
10275 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010276 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010277 PyUnicode_GET_LENGTH(self), maxcount
10278 );
10279 else
10280 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010281 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010282 PyUnicode_GET_LENGTH(self), maxcount
10283 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 case PyUnicode_2BYTE_KIND:
10285 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010286 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 PyUnicode_GET_LENGTH(self), maxcount
10288 );
10289 case PyUnicode_4BYTE_KIND:
10290 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010291 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 PyUnicode_GET_LENGTH(self), maxcount
10293 );
10294 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010295 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010296 }
10297
10298 if (PyUnicode_READY(substring) == -1)
10299 return NULL;
10300
10301 kind1 = PyUnicode_KIND(self);
10302 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 len1 = PyUnicode_GET_LENGTH(self);
10304 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010305 if (kind1 < kind2 || len1 < len2) {
10306 out = PyList_New(1);
10307 if (out == NULL)
10308 return NULL;
10309 Py_INCREF(self);
10310 PyList_SET_ITEM(out, 0, self);
10311 return out;
10312 }
10313 buf1 = PyUnicode_DATA(self);
10314 buf2 = PyUnicode_DATA(substring);
10315 if (kind2 != kind1) {
10316 buf2 = _PyUnicode_AsKind(substring, kind1);
10317 if (!buf2)
10318 return NULL;
10319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010321 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010323 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10324 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010325 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010326 else
10327 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010328 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 break;
10330 case PyUnicode_2BYTE_KIND:
10331 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010332 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010333 break;
10334 case PyUnicode_4BYTE_KIND:
10335 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010336 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 break;
10338 default:
10339 out = NULL;
10340 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010341 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 PyMem_Free(buf2);
10343 return out;
10344}
10345
10346static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010347anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10348 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010350 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010352 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10353 return asciilib_find(buf1, len1, buf2, len2, offset);
10354 else
10355 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 case PyUnicode_2BYTE_KIND:
10357 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10358 case PyUnicode_4BYTE_KIND:
10359 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10360 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010361 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010362}
10363
10364static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010365anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10366 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010368 switch (kind) {
10369 case PyUnicode_1BYTE_KIND:
10370 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10371 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10372 else
10373 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10374 case PyUnicode_2BYTE_KIND:
10375 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10376 case PyUnicode_4BYTE_KIND:
10377 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10378 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010379 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010380}
10381
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010382static void
10383replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10384 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10385{
10386 int kind = PyUnicode_KIND(u);
10387 void *data = PyUnicode_DATA(u);
10388 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10389 if (kind == PyUnicode_1BYTE_KIND) {
10390 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10391 (Py_UCS1 *)data + len,
10392 u1, u2, maxcount);
10393 }
10394 else if (kind == PyUnicode_2BYTE_KIND) {
10395 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10396 (Py_UCS2 *)data + len,
10397 u1, u2, maxcount);
10398 }
10399 else {
10400 assert(kind == PyUnicode_4BYTE_KIND);
10401 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10402 (Py_UCS4 *)data + len,
10403 u1, u2, maxcount);
10404 }
10405}
10406
Alexander Belopolsky40018472011-02-26 01:02:56 +000010407static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408replace(PyObject *self, PyObject *str1,
10409 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010410{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 PyObject *u;
10412 char *sbuf = PyUnicode_DATA(self);
10413 char *buf1 = PyUnicode_DATA(str1);
10414 char *buf2 = PyUnicode_DATA(str2);
10415 int srelease = 0, release1 = 0, release2 = 0;
10416 int skind = PyUnicode_KIND(self);
10417 int kind1 = PyUnicode_KIND(str1);
10418 int kind2 = PyUnicode_KIND(str2);
10419 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10420 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10421 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010422 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010423 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010424
10425 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010426 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010428 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010429
Victor Stinner59de0ee2011-10-07 10:01:28 +020010430 if (str1 == str2)
10431 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432
Victor Stinner49a0a212011-10-12 23:46:10 +020010433 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010434 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10435 if (maxchar < maxchar_str1)
10436 /* substring too wide to be present */
10437 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010438 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10439 /* Replacing str1 with str2 may cause a maxchar reduction in the
10440 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010441 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010442 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010445 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010446 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010447 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010449 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010450 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010451 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010452
Victor Stinner69ed0f42013-04-09 21:48:24 +020010453 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010454 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010455 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010456 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010457 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010459 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010461
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010462 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10463 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010464 }
10465 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 int rkind = skind;
10467 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010468 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010470 if (kind1 < rkind) {
10471 /* widen substring */
10472 buf1 = _PyUnicode_AsKind(str1, rkind);
10473 if (!buf1) goto error;
10474 release1 = 1;
10475 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010476 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010477 if (i < 0)
10478 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 if (rkind > kind2) {
10480 /* widen replacement */
10481 buf2 = _PyUnicode_AsKind(str2, rkind);
10482 if (!buf2) goto error;
10483 release2 = 1;
10484 }
10485 else if (rkind < kind2) {
10486 /* widen self and buf1 */
10487 rkind = kind2;
10488 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010489 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 sbuf = _PyUnicode_AsKind(self, rkind);
10491 if (!sbuf) goto error;
10492 srelease = 1;
10493 buf1 = _PyUnicode_AsKind(str1, rkind);
10494 if (!buf1) goto error;
10495 release1 = 1;
10496 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010497 u = PyUnicode_New(slen, maxchar);
10498 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010499 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010500 assert(PyUnicode_KIND(u) == rkind);
10501 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010502
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010503 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010504 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010505 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010507 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010509
10510 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010511 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010512 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010513 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010514 if (i == -1)
10515 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010516 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010518 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010519 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010520 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010521 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010522 }
10523 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010525 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010526 int rkind = skind;
10527 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010530 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 buf1 = _PyUnicode_AsKind(str1, rkind);
10532 if (!buf1) goto error;
10533 release1 = 1;
10534 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010535 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010536 if (n == 0)
10537 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010538 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010539 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 buf2 = _PyUnicode_AsKind(str2, rkind);
10541 if (!buf2) goto error;
10542 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010544 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010545 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 rkind = kind2;
10547 sbuf = _PyUnicode_AsKind(self, rkind);
10548 if (!sbuf) goto error;
10549 srelease = 1;
10550 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010551 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 buf1 = _PyUnicode_AsKind(str1, rkind);
10553 if (!buf1) goto error;
10554 release1 = 1;
10555 }
10556 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10557 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010558 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 PyErr_SetString(PyExc_OverflowError,
10560 "replace string is too long");
10561 goto error;
10562 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010563 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010564 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010565 _Py_INCREF_UNICODE_EMPTY();
10566 if (!unicode_empty)
10567 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010568 u = unicode_empty;
10569 goto done;
10570 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010571 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 PyErr_SetString(PyExc_OverflowError,
10573 "replace string is too long");
10574 goto error;
10575 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010576 u = PyUnicode_New(new_size, maxchar);
10577 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010579 assert(PyUnicode_KIND(u) == rkind);
10580 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 ires = i = 0;
10582 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010583 while (n-- > 0) {
10584 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010585 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010586 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010587 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010588 if (j == -1)
10589 break;
10590 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010591 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010592 memcpy(res + rkind * ires,
10593 sbuf + rkind * i,
10594 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010596 }
10597 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010599 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010601 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010603 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010605 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010607 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010608 memcpy(res + rkind * ires,
10609 sbuf + rkind * i,
10610 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010611 }
10612 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010613 /* interleave */
10614 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010615 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010617 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010619 if (--n <= 0)
10620 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010621 memcpy(res + rkind * ires,
10622 sbuf + rkind * i,
10623 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 ires++;
10625 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010626 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010627 memcpy(res + rkind * ires,
10628 sbuf + rkind * i,
10629 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010630 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010631 }
10632
10633 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010634 unicode_adjust_maxchar(&u);
10635 if (u == NULL)
10636 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010637 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010638
10639 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010640 if (srelease)
10641 PyMem_FREE(sbuf);
10642 if (release1)
10643 PyMem_FREE(buf1);
10644 if (release2)
10645 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010646 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010648
Benjamin Peterson29060642009-01-31 22:14:21 +000010649 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010650 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 if (srelease)
10652 PyMem_FREE(sbuf);
10653 if (release1)
10654 PyMem_FREE(buf1);
10655 if (release2)
10656 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010657 return unicode_result_unchanged(self);
10658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 error:
10660 if (srelease && sbuf)
10661 PyMem_FREE(sbuf);
10662 if (release1 && buf1)
10663 PyMem_FREE(buf1);
10664 if (release2 && buf2)
10665 PyMem_FREE(buf2);
10666 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010667}
10668
10669/* --- Unicode Object Methods --------------------------------------------- */
10670
INADA Naoki3ae20562017-01-16 20:41:20 +090010671/*[clinic input]
10672str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010673
INADA Naoki3ae20562017-01-16 20:41:20 +090010674Return a version of the string where each word is titlecased.
10675
10676More specifically, words start with uppercased characters and all remaining
10677cased characters have lower case.
10678[clinic start generated code]*/
10679
10680static PyObject *
10681unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010682/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010683{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010684 if (PyUnicode_READY(self) == -1)
10685 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010686 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010687}
10688
INADA Naoki3ae20562017-01-16 20:41:20 +090010689/*[clinic input]
10690str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010691
INADA Naoki3ae20562017-01-16 20:41:20 +090010692Return a capitalized version of the string.
10693
10694More specifically, make the first character have upper case and the rest lower
10695case.
10696[clinic start generated code]*/
10697
10698static PyObject *
10699unicode_capitalize_impl(PyObject *self)
10700/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010702 if (PyUnicode_READY(self) == -1)
10703 return NULL;
10704 if (PyUnicode_GET_LENGTH(self) == 0)
10705 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010706 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010707}
10708
INADA Naoki3ae20562017-01-16 20:41:20 +090010709/*[clinic input]
10710str.casefold as unicode_casefold
10711
10712Return a version of the string suitable for caseless comparisons.
10713[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010714
10715static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010716unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010717/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010718{
10719 if (PyUnicode_READY(self) == -1)
10720 return NULL;
10721 if (PyUnicode_IS_ASCII(self))
10722 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010723 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010724}
10725
10726
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010727/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010728
10729static int
10730convert_uc(PyObject *obj, void *addr)
10731{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010732 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010733
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010734 if (!PyUnicode_Check(obj)) {
10735 PyErr_Format(PyExc_TypeError,
10736 "The fill character must be a unicode character, "
Victor Stinner998b8062018-09-12 00:23:25 +020010737 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010738 return 0;
10739 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010740 if (PyUnicode_READY(obj) < 0)
10741 return 0;
10742 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010743 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010744 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010745 return 0;
10746 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010747 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010748 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010749}
10750
INADA Naoki3ae20562017-01-16 20:41:20 +090010751/*[clinic input]
10752str.center as unicode_center
10753
10754 width: Py_ssize_t
10755 fillchar: Py_UCS4 = ' '
10756 /
10757
10758Return a centered string of length width.
10759
10760Padding is done using the specified fill character (default is a space).
10761[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010762
10763static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010764unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10765/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010767 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768
Benjamin Petersonbac79492012-01-14 13:34:47 -050010769 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010770 return NULL;
10771
Victor Stinnerc4b49542011-12-11 22:44:26 +010010772 if (PyUnicode_GET_LENGTH(self) >= width)
10773 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010774
Victor Stinnerc4b49542011-12-11 22:44:26 +010010775 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776 left = marg / 2 + (marg & width & 1);
10777
Victor Stinner9310abb2011-10-05 00:59:23 +020010778 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010779}
10780
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010781/* This function assumes that str1 and str2 are readied by the caller. */
10782
Marc-André Lemburge5034372000-08-08 08:04:29 +000010783static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010784unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010785{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010786#define COMPARE(TYPE1, TYPE2) \
10787 do { \
10788 TYPE1* p1 = (TYPE1 *)data1; \
10789 TYPE2* p2 = (TYPE2 *)data2; \
10790 TYPE1* end = p1 + len; \
10791 Py_UCS4 c1, c2; \
10792 for (; p1 != end; p1++, p2++) { \
10793 c1 = *p1; \
10794 c2 = *p2; \
10795 if (c1 != c2) \
10796 return (c1 < c2) ? -1 : 1; \
10797 } \
10798 } \
10799 while (0)
10800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 int kind1, kind2;
10802 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010803 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010805 kind1 = PyUnicode_KIND(str1);
10806 kind2 = PyUnicode_KIND(str2);
10807 data1 = PyUnicode_DATA(str1);
10808 data2 = PyUnicode_DATA(str2);
10809 len1 = PyUnicode_GET_LENGTH(str1);
10810 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010811 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010812
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010813 switch(kind1) {
10814 case PyUnicode_1BYTE_KIND:
10815 {
10816 switch(kind2) {
10817 case PyUnicode_1BYTE_KIND:
10818 {
10819 int cmp = memcmp(data1, data2, len);
10820 /* normalize result of memcmp() into the range [-1; 1] */
10821 if (cmp < 0)
10822 return -1;
10823 if (cmp > 0)
10824 return 1;
10825 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010826 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010827 case PyUnicode_2BYTE_KIND:
10828 COMPARE(Py_UCS1, Py_UCS2);
10829 break;
10830 case PyUnicode_4BYTE_KIND:
10831 COMPARE(Py_UCS1, Py_UCS4);
10832 break;
10833 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010834 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010835 }
10836 break;
10837 }
10838 case PyUnicode_2BYTE_KIND:
10839 {
10840 switch(kind2) {
10841 case PyUnicode_1BYTE_KIND:
10842 COMPARE(Py_UCS2, Py_UCS1);
10843 break;
10844 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010845 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010846 COMPARE(Py_UCS2, Py_UCS2);
10847 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010848 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010849 case PyUnicode_4BYTE_KIND:
10850 COMPARE(Py_UCS2, Py_UCS4);
10851 break;
10852 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010853 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010854 }
10855 break;
10856 }
10857 case PyUnicode_4BYTE_KIND:
10858 {
10859 switch(kind2) {
10860 case PyUnicode_1BYTE_KIND:
10861 COMPARE(Py_UCS4, Py_UCS1);
10862 break;
10863 case PyUnicode_2BYTE_KIND:
10864 COMPARE(Py_UCS4, Py_UCS2);
10865 break;
10866 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010867 {
10868#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10869 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10870 /* normalize result of wmemcmp() into the range [-1; 1] */
10871 if (cmp < 0)
10872 return -1;
10873 if (cmp > 0)
10874 return 1;
10875#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010876 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010877#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010878 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010879 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010880 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010881 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010882 }
10883 break;
10884 }
10885 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010886 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010887 }
10888
Victor Stinner770e19e2012-10-04 22:59:45 +020010889 if (len1 == len2)
10890 return 0;
10891 if (len1 < len2)
10892 return -1;
10893 else
10894 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010895
10896#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010897}
10898
Benjamin Peterson621b4302016-09-09 13:54:34 -070010899static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010900unicode_compare_eq(PyObject *str1, PyObject *str2)
10901{
10902 int kind;
10903 void *data1, *data2;
10904 Py_ssize_t len;
10905 int cmp;
10906
Victor Stinnere5567ad2012-10-23 02:48:49 +020010907 len = PyUnicode_GET_LENGTH(str1);
10908 if (PyUnicode_GET_LENGTH(str2) != len)
10909 return 0;
10910 kind = PyUnicode_KIND(str1);
10911 if (PyUnicode_KIND(str2) != kind)
10912 return 0;
10913 data1 = PyUnicode_DATA(str1);
10914 data2 = PyUnicode_DATA(str2);
10915
10916 cmp = memcmp(data1, data2, len * kind);
10917 return (cmp == 0);
10918}
10919
10920
Alexander Belopolsky40018472011-02-26 01:02:56 +000010921int
10922PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010924 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10925 if (PyUnicode_READY(left) == -1 ||
10926 PyUnicode_READY(right) == -1)
10927 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010010928
10929 /* a string is equal to itself */
10930 if (left == right)
10931 return 0;
10932
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010933 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010934 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010935 PyErr_Format(PyExc_TypeError,
10936 "Can't compare %.100s and %.100s",
10937 left->ob_type->tp_name,
10938 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939 return -1;
10940}
10941
Martin v. Löwis5b222132007-06-10 09:51:05 +000010942int
10943PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10944{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010945 Py_ssize_t i;
10946 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010947 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010948 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010949
Victor Stinner910337b2011-10-03 03:20:16 +020010950 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020010951 if (!PyUnicode_IS_READY(uni)) {
10952 const wchar_t *ws = _PyUnicode_WSTR(uni);
10953 /* Compare Unicode string and source character set string */
10954 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
10955 if (chr != ustr[i])
10956 return (chr < ustr[i]) ? -1 : 1;
10957 }
10958 /* This check keeps Python strings that end in '\0' from comparing equal
10959 to C strings identical up to that point. */
10960 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
10961 return 1; /* uni is longer */
10962 if (ustr[i])
10963 return -1; /* str is longer */
10964 return 0;
10965 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010966 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010967 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010010968 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010010969 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010010970 size_t len, len2 = strlen(str);
10971 int cmp;
10972
10973 len = Py_MIN(len1, len2);
10974 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010010975 if (cmp != 0) {
10976 if (cmp < 0)
10977 return -1;
10978 else
10979 return 1;
10980 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010010981 if (len1 > len2)
10982 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010983 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010010984 return -1; /* str is longer */
10985 return 0;
10986 }
10987 else {
10988 void *data = PyUnicode_DATA(uni);
10989 /* Compare Unicode string and source character set string */
10990 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020010991 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010010992 return (chr < (unsigned char)(str[i])) ? -1 : 1;
10993 /* This check keeps Python strings that end in '\0' from comparing equal
10994 to C strings identical up to that point. */
10995 if (PyUnicode_GET_LENGTH(uni) != i || chr)
10996 return 1; /* uni is longer */
10997 if (str[i])
10998 return -1; /* str is longer */
10999 return 0;
11000 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011001}
11002
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011003static int
11004non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11005{
11006 size_t i, len;
11007 const wchar_t *p;
11008 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11009 if (strlen(str) != len)
11010 return 0;
11011 p = _PyUnicode_WSTR(unicode);
11012 assert(p);
11013 for (i = 0; i < len; i++) {
11014 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011015 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011016 return 0;
11017 }
11018 return 1;
11019}
11020
11021int
11022_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11023{
11024 size_t len;
11025 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011026 assert(str);
11027#ifndef NDEBUG
11028 for (const char *p = str; *p; p++) {
11029 assert((unsigned char)*p < 128);
11030 }
11031#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011032 if (PyUnicode_READY(unicode) == -1) {
11033 /* Memory error or bad data */
11034 PyErr_Clear();
11035 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11036 }
11037 if (!PyUnicode_IS_ASCII(unicode))
11038 return 0;
11039 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11040 return strlen(str) == len &&
11041 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11042}
11043
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011044int
11045_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11046{
11047 PyObject *right_uni;
11048 Py_hash_t hash;
11049
11050 assert(_PyUnicode_CHECK(left));
11051 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011052#ifndef NDEBUG
11053 for (const char *p = right->string; *p; p++) {
11054 assert((unsigned char)*p < 128);
11055 }
11056#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011057
11058 if (PyUnicode_READY(left) == -1) {
11059 /* memory error or bad data */
11060 PyErr_Clear();
11061 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11062 }
11063
11064 if (!PyUnicode_IS_ASCII(left))
11065 return 0;
11066
11067 right_uni = _PyUnicode_FromId(right); /* borrowed */
11068 if (right_uni == NULL) {
11069 /* memory error or bad data */
11070 PyErr_Clear();
11071 return _PyUnicode_EqualToASCIIString(left, right->string);
11072 }
11073
11074 if (left == right_uni)
11075 return 1;
11076
11077 if (PyUnicode_CHECK_INTERNED(left))
11078 return 0;
11079
INADA Naoki7cc95f52018-01-28 02:07:09 +090011080 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011081 hash = _PyUnicode_HASH(left);
11082 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11083 return 0;
11084
11085 return unicode_compare_eq(left, right_uni);
11086}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011087
Alexander Belopolsky40018472011-02-26 01:02:56 +000011088PyObject *
11089PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011090{
11091 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011092
Victor Stinnere5567ad2012-10-23 02:48:49 +020011093 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11094 Py_RETURN_NOTIMPLEMENTED;
11095
11096 if (PyUnicode_READY(left) == -1 ||
11097 PyUnicode_READY(right) == -1)
11098 return NULL;
11099
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011100 if (left == right) {
11101 switch (op) {
11102 case Py_EQ:
11103 case Py_LE:
11104 case Py_GE:
11105 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011106 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011107 case Py_NE:
11108 case Py_LT:
11109 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011110 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011111 default:
11112 PyErr_BadArgument();
11113 return NULL;
11114 }
11115 }
11116 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011117 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011118 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011119 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011120 }
11121 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011122 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011123 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011124 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011125}
11126
Alexander Belopolsky40018472011-02-26 01:02:56 +000011127int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011128_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11129{
11130 return unicode_eq(aa, bb);
11131}
11132
11133int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011134PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011135{
Victor Stinner77282cb2013-04-14 19:22:47 +020011136 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011137 void *buf1, *buf2;
11138 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011139 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011140
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011141 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011142 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020011143 "'in <string>' requires string as left operand, not %.100s",
11144 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011145 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011146 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011147 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011148 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011149 if (ensure_unicode(str) < 0)
11150 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011151
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011152 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011153 kind2 = PyUnicode_KIND(substr);
11154 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011155 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011157 len2 = PyUnicode_GET_LENGTH(substr);
11158 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011159 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011160 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011161 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011162 if (len2 == 1) {
11163 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11164 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011165 return result;
11166 }
11167 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011168 buf2 = _PyUnicode_AsKind(substr, kind1);
11169 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011170 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172
Victor Stinner77282cb2013-04-14 19:22:47 +020011173 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011174 case PyUnicode_1BYTE_KIND:
11175 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11176 break;
11177 case PyUnicode_2BYTE_KIND:
11178 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11179 break;
11180 case PyUnicode_4BYTE_KIND:
11181 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11182 break;
11183 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011184 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011186
Victor Stinner77282cb2013-04-14 19:22:47 +020011187 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011188 PyMem_Free(buf2);
11189
Guido van Rossum403d68b2000-03-13 15:55:09 +000011190 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011191}
11192
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193/* Concat to string or Unicode object giving a new Unicode object. */
11194
Alexander Belopolsky40018472011-02-26 01:02:56 +000011195PyObject *
11196PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011198 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011199 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011200 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011202 if (ensure_unicode(left) < 0)
11203 return NULL;
11204
11205 if (!PyUnicode_Check(right)) {
11206 PyErr_Format(PyExc_TypeError,
11207 "can only concatenate str (not \"%.200s\") to str",
11208 right->ob_type->tp_name);
11209 return NULL;
11210 }
11211 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011212 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213
11214 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011215 if (left == unicode_empty)
11216 return PyUnicode_FromObject(right);
11217 if (right == unicode_empty)
11218 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011220 left_len = PyUnicode_GET_LENGTH(left);
11221 right_len = PyUnicode_GET_LENGTH(right);
11222 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011223 PyErr_SetString(PyExc_OverflowError,
11224 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011225 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011226 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011227 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011228
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011229 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11230 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011231 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011234 result = PyUnicode_New(new_len, maxchar);
11235 if (result == NULL)
11236 return NULL;
11237 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11238 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11239 assert(_PyUnicode_CheckConsistency(result, 1));
11240 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241}
11242
Walter Dörwald1ab83302007-05-18 17:15:44 +000011243void
Victor Stinner23e56682011-10-03 03:54:37 +020011244PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011245{
Victor Stinner23e56682011-10-03 03:54:37 +020011246 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011247 Py_UCS4 maxchar, maxchar2;
11248 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011249
11250 if (p_left == NULL) {
11251 if (!PyErr_Occurred())
11252 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011253 return;
11254 }
Victor Stinner23e56682011-10-03 03:54:37 +020011255 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011256 if (right == NULL || left == NULL
11257 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011258 if (!PyErr_Occurred())
11259 PyErr_BadInternalCall();
11260 goto error;
11261 }
11262
Benjamin Petersonbac79492012-01-14 13:34:47 -050011263 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011264 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011265 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011266 goto error;
11267
Victor Stinner488fa492011-12-12 00:01:39 +010011268 /* Shortcuts */
11269 if (left == unicode_empty) {
11270 Py_DECREF(left);
11271 Py_INCREF(right);
11272 *p_left = right;
11273 return;
11274 }
11275 if (right == unicode_empty)
11276 return;
11277
11278 left_len = PyUnicode_GET_LENGTH(left);
11279 right_len = PyUnicode_GET_LENGTH(right);
11280 if (left_len > PY_SSIZE_T_MAX - right_len) {
11281 PyErr_SetString(PyExc_OverflowError,
11282 "strings are too large to concat");
11283 goto error;
11284 }
11285 new_len = left_len + right_len;
11286
11287 if (unicode_modifiable(left)
11288 && PyUnicode_CheckExact(right)
11289 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011290 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11291 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011292 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011293 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011294 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11295 {
11296 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011297 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011298 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011299
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011300 /* copy 'right' into the newly allocated area of 'left' */
11301 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011302 }
Victor Stinner488fa492011-12-12 00:01:39 +010011303 else {
11304 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11305 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011306 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011307
Victor Stinner488fa492011-12-12 00:01:39 +010011308 /* Concat the two Unicode strings */
11309 res = PyUnicode_New(new_len, maxchar);
11310 if (res == NULL)
11311 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011312 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11313 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011314 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011315 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011316 }
11317 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011318 return;
11319
11320error:
Victor Stinner488fa492011-12-12 00:01:39 +010011321 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011322}
11323
11324void
11325PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11326{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011327 PyUnicode_Append(pleft, right);
11328 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011329}
11330
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011331/*
11332Wraps stringlib_parse_args_finds() and additionally ensures that the
11333first argument is a unicode object.
11334*/
11335
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011336static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011337parse_args_finds_unicode(const char * function_name, PyObject *args,
11338 PyObject **substring,
11339 Py_ssize_t *start, Py_ssize_t *end)
11340{
11341 if(stringlib_parse_args_finds(function_name, args, substring,
11342 start, end)) {
11343 if (ensure_unicode(*substring) < 0)
11344 return 0;
11345 return 1;
11346 }
11347 return 0;
11348}
11349
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011350PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011351 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011353Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011354string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011355interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011356
11357static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011358unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011360 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011361 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011362 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011364 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 void *buf1, *buf2;
11366 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011368 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011369 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 kind1 = PyUnicode_KIND(self);
11372 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011373 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011374 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011375
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 len1 = PyUnicode_GET_LENGTH(self);
11377 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011378 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011379 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011380 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011381
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011382 buf1 = PyUnicode_DATA(self);
11383 buf2 = PyUnicode_DATA(substring);
11384 if (kind2 != kind1) {
11385 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011386 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011387 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011388 }
11389 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011390 case PyUnicode_1BYTE_KIND:
11391 iresult = ucs1lib_count(
11392 ((Py_UCS1*)buf1) + start, end - start,
11393 buf2, len2, PY_SSIZE_T_MAX
11394 );
11395 break;
11396 case PyUnicode_2BYTE_KIND:
11397 iresult = ucs2lib_count(
11398 ((Py_UCS2*)buf1) + start, end - start,
11399 buf2, len2, PY_SSIZE_T_MAX
11400 );
11401 break;
11402 case PyUnicode_4BYTE_KIND:
11403 iresult = ucs4lib_count(
11404 ((Py_UCS4*)buf1) + start, end - start,
11405 buf2, len2, PY_SSIZE_T_MAX
11406 );
11407 break;
11408 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011409 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011410 }
11411
11412 result = PyLong_FromSsize_t(iresult);
11413
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011414 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011415 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417 return result;
11418}
11419
INADA Naoki3ae20562017-01-16 20:41:20 +090011420/*[clinic input]
11421str.encode as unicode_encode
11422
11423 encoding: str(c_default="NULL") = 'utf-8'
11424 The encoding in which to encode the string.
11425 errors: str(c_default="NULL") = 'strict'
11426 The error handling scheme to use for encoding errors.
11427 The default is 'strict' meaning that encoding errors raise a
11428 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11429 'xmlcharrefreplace' as well as any other name registered with
11430 codecs.register_error that can handle UnicodeEncodeErrors.
11431
11432Encode the string using the codec registered for encoding.
11433[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434
11435static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011436unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011437/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011438{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011439 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011440}
11441
INADA Naoki3ae20562017-01-16 20:41:20 +090011442/*[clinic input]
11443str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
INADA Naoki3ae20562017-01-16 20:41:20 +090011445 tabsize: int = 8
11446
11447Return a copy where all tab characters are expanded using spaces.
11448
11449If tabsize is not given, a tab size of 8 characters is assumed.
11450[clinic start generated code]*/
11451
11452static PyObject *
11453unicode_expandtabs_impl(PyObject *self, int tabsize)
11454/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011456 Py_ssize_t i, j, line_pos, src_len, incr;
11457 Py_UCS4 ch;
11458 PyObject *u;
11459 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011460 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011461 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Antoine Pitrou22425222011-10-04 19:10:51 +020011463 if (PyUnicode_READY(self) == -1)
11464 return NULL;
11465
Thomas Wouters7e474022000-07-16 12:04:32 +000011466 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011467 src_len = PyUnicode_GET_LENGTH(self);
11468 i = j = line_pos = 0;
11469 kind = PyUnicode_KIND(self);
11470 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011471 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011472 for (; i < src_len; i++) {
11473 ch = PyUnicode_READ(kind, src_data, i);
11474 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011475 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011477 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011479 goto overflow;
11480 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011482 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011483 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011484 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011486 goto overflow;
11487 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011489 if (ch == '\n' || ch == '\r')
11490 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011492 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011493 if (!found)
11494 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011495
Guido van Rossumd57fd912000-03-10 22:53:23 +000011496 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011497 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011498 if (!u)
11499 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011500 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011501
Antoine Pitroue71d5742011-10-04 15:55:09 +020011502 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503
Antoine Pitroue71d5742011-10-04 15:55:09 +020011504 for (; i < src_len; i++) {
11505 ch = PyUnicode_READ(kind, src_data, i);
11506 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011508 incr = tabsize - (line_pos % tabsize);
11509 line_pos += incr;
Victor Stinner59423e32018-11-26 13:40:01 +010011510 unicode_fill(kind, dest_data, ' ', j, incr);
Victor Stinnerda79e632012-02-22 13:37:04 +010011511 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011513 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011514 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011515 line_pos++;
11516 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011517 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011518 if (ch == '\n' || ch == '\r')
11519 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011521 }
11522 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011523 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011524
Antoine Pitroue71d5742011-10-04 15:55:09 +020011525 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011526 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11527 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528}
11529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011530PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011531 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532\n\
11533Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011534such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535arguments start and end are interpreted as in slice notation.\n\
11536\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011537Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538
11539static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011540unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011542 /* initialize variables to prevent gcc warning */
11543 PyObject *substring = NULL;
11544 Py_ssize_t start = 0;
11545 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011546 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011548 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011551 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011553
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011554 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 if (result == -2)
11557 return NULL;
11558
Christian Heimes217cfd12007-12-02 14:31:20 +000011559 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560}
11561
11562static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011563unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011565 void *data;
11566 enum PyUnicode_Kind kind;
11567 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011568
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011569 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011570 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011571 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011572 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011573 if (PyUnicode_READY(self) == -1) {
11574 return NULL;
11575 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011576 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11577 PyErr_SetString(PyExc_IndexError, "string index out of range");
11578 return NULL;
11579 }
11580 kind = PyUnicode_KIND(self);
11581 data = PyUnicode_DATA(self);
11582 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011583 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584}
11585
Guido van Rossumc2504932007-09-18 19:42:40 +000011586/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011587 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011588static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011589unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590{
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011591 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011592
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011593#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011594 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011595#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 if (_PyUnicode_HASH(self) != -1)
11597 return _PyUnicode_HASH(self);
11598 if (PyUnicode_READY(self) == -1)
11599 return -1;
animalizea1d14252019-01-02 20:16:06 +080011600
Christian Heimes985ecdc2013-11-20 11:46:18 +010011601 x = _Py_HashBytes(PyUnicode_DATA(self),
11602 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011604 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605}
11606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011607PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011608 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609\n\
oldkaa0735f2018-02-02 16:52:55 +080011610Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011611such that sub is contained within S[start:end]. Optional\n\
11612arguments start and end are interpreted as in slice notation.\n\
11613\n\
11614Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615
11616static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011619 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011620 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011621 PyObject *substring = NULL;
11622 Py_ssize_t start = 0;
11623 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011625 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011628 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011631 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011632
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 if (result == -2)
11634 return NULL;
11635
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636 if (result < 0) {
11637 PyErr_SetString(PyExc_ValueError, "substring not found");
11638 return NULL;
11639 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011640
Christian Heimes217cfd12007-12-02 14:31:20 +000011641 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642}
11643
INADA Naoki3ae20562017-01-16 20:41:20 +090011644/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011645str.isascii as unicode_isascii
11646
11647Return True if all characters in the string are ASCII, False otherwise.
11648
11649ASCII characters have code points in the range U+0000-U+007F.
11650Empty string is ASCII too.
11651[clinic start generated code]*/
11652
11653static PyObject *
11654unicode_isascii_impl(PyObject *self)
11655/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11656{
11657 if (PyUnicode_READY(self) == -1) {
11658 return NULL;
11659 }
11660 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11661}
11662
11663/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011664str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011665
INADA Naoki3ae20562017-01-16 20:41:20 +090011666Return True if the string is a lowercase string, False otherwise.
11667
11668A string is lowercase if all cased characters in the string are lowercase and
11669there is at least one cased character in the string.
11670[clinic start generated code]*/
11671
11672static PyObject *
11673unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011674/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011676 Py_ssize_t i, length;
11677 int kind;
11678 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011679 int cased;
11680
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (PyUnicode_READY(self) == -1)
11682 return NULL;
11683 length = PyUnicode_GET_LENGTH(self);
11684 kind = PyUnicode_KIND(self);
11685 data = PyUnicode_DATA(self);
11686
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 if (length == 1)
11689 return PyBool_FromLong(
11690 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011692 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011694 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011695
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 for (i = 0; i < length; i++) {
11698 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011699
Benjamin Peterson29060642009-01-31 22:14:21 +000011700 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011701 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011702 else if (!cased && Py_UNICODE_ISLOWER(ch))
11703 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011705 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706}
11707
INADA Naoki3ae20562017-01-16 20:41:20 +090011708/*[clinic input]
11709str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710
INADA Naoki3ae20562017-01-16 20:41:20 +090011711Return True if the string is an uppercase string, False otherwise.
11712
11713A string is uppercase if all cased characters in the string are uppercase and
11714there is at least one cased character in the string.
11715[clinic start generated code]*/
11716
11717static PyObject *
11718unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011719/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721 Py_ssize_t i, length;
11722 int kind;
11723 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011724 int cased;
11725
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 if (PyUnicode_READY(self) == -1)
11727 return NULL;
11728 length = PyUnicode_GET_LENGTH(self);
11729 kind = PyUnicode_KIND(self);
11730 data = PyUnicode_DATA(self);
11731
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011733 if (length == 1)
11734 return PyBool_FromLong(
11735 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011737 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011738 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011739 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011740
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011742 for (i = 0; i < length; i++) {
11743 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011744
Benjamin Peterson29060642009-01-31 22:14:21 +000011745 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011746 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011747 else if (!cased && Py_UNICODE_ISUPPER(ch))
11748 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011749 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011750 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751}
11752
INADA Naoki3ae20562017-01-16 20:41:20 +090011753/*[clinic input]
11754str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755
INADA Naoki3ae20562017-01-16 20:41:20 +090011756Return True if the string is a title-cased string, False otherwise.
11757
11758In a title-cased string, upper- and title-case characters may only
11759follow uncased characters and lowercase characters only cased ones.
11760[clinic start generated code]*/
11761
11762static PyObject *
11763unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011764/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766 Py_ssize_t i, length;
11767 int kind;
11768 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011769 int cased, previous_is_cased;
11770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 if (PyUnicode_READY(self) == -1)
11772 return NULL;
11773 length = PyUnicode_GET_LENGTH(self);
11774 kind = PyUnicode_KIND(self);
11775 data = PyUnicode_DATA(self);
11776
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778 if (length == 1) {
11779 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11780 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11781 (Py_UNICODE_ISUPPER(ch) != 0));
11782 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011784 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011786 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011787
Guido van Rossumd57fd912000-03-10 22:53:23 +000011788 cased = 0;
11789 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 for (i = 0; i < length; i++) {
11791 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011792
Benjamin Peterson29060642009-01-31 22:14:21 +000011793 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11794 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011795 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011796 previous_is_cased = 1;
11797 cased = 1;
11798 }
11799 else if (Py_UNICODE_ISLOWER(ch)) {
11800 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011801 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011802 previous_is_cased = 1;
11803 cased = 1;
11804 }
11805 else
11806 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011807 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011808 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809}
11810
INADA Naoki3ae20562017-01-16 20:41:20 +090011811/*[clinic input]
11812str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011813
INADA Naoki3ae20562017-01-16 20:41:20 +090011814Return True if the string is a whitespace string, False otherwise.
11815
11816A string is whitespace if all characters in the string are whitespace and there
11817is at least one character in the string.
11818[clinic start generated code]*/
11819
11820static PyObject *
11821unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011822/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011823{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 Py_ssize_t i, length;
11825 int kind;
11826 void *data;
11827
11828 if (PyUnicode_READY(self) == -1)
11829 return NULL;
11830 length = PyUnicode_GET_LENGTH(self);
11831 kind = PyUnicode_KIND(self);
11832 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 if (length == 1)
11836 return PyBool_FromLong(
11837 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011838
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011839 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011841 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011842
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011843 for (i = 0; i < length; i++) {
11844 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011845 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011846 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011847 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011848 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849}
11850
INADA Naoki3ae20562017-01-16 20:41:20 +090011851/*[clinic input]
11852str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011853
INADA Naoki3ae20562017-01-16 20:41:20 +090011854Return True if the string is an alphabetic string, False otherwise.
11855
11856A string is alphabetic if all characters in the string are alphabetic and there
11857is at least one character in the string.
11858[clinic start generated code]*/
11859
11860static PyObject *
11861unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011862/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011863{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 Py_ssize_t i, length;
11865 int kind;
11866 void *data;
11867
11868 if (PyUnicode_READY(self) == -1)
11869 return NULL;
11870 length = PyUnicode_GET_LENGTH(self);
11871 kind = PyUnicode_KIND(self);
11872 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011873
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011874 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 if (length == 1)
11876 return PyBool_FromLong(
11877 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011878
11879 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011880 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011881 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 for (i = 0; i < length; i++) {
11884 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011885 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011886 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011887 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011888}
11889
INADA Naoki3ae20562017-01-16 20:41:20 +090011890/*[clinic input]
11891str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011892
INADA Naoki3ae20562017-01-16 20:41:20 +090011893Return True if the string is an alpha-numeric string, False otherwise.
11894
11895A string is alpha-numeric if all characters in the string are alpha-numeric and
11896there is at least one character in the string.
11897[clinic start generated code]*/
11898
11899static PyObject *
11900unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011901/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011902{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 int kind;
11904 void *data;
11905 Py_ssize_t len, i;
11906
11907 if (PyUnicode_READY(self) == -1)
11908 return NULL;
11909
11910 kind = PyUnicode_KIND(self);
11911 data = PyUnicode_DATA(self);
11912 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011913
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011914 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 if (len == 1) {
11916 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11917 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11918 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011919
11920 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011921 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011922 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011923
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011924 for (i = 0; i < len; i++) {
11925 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011926 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011927 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011928 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011929 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011930}
11931
INADA Naoki3ae20562017-01-16 20:41:20 +090011932/*[clinic input]
11933str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934
INADA Naoki3ae20562017-01-16 20:41:20 +090011935Return True if the string is a decimal string, False otherwise.
11936
11937A string is a decimal string if all characters in the string are decimal and
11938there is at least one character in the string.
11939[clinic start generated code]*/
11940
11941static PyObject *
11942unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011943/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011944{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945 Py_ssize_t i, length;
11946 int kind;
11947 void *data;
11948
11949 if (PyUnicode_READY(self) == -1)
11950 return NULL;
11951 length = PyUnicode_GET_LENGTH(self);
11952 kind = PyUnicode_KIND(self);
11953 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011954
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011956 if (length == 1)
11957 return PyBool_FromLong(
11958 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011960 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011962 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011963
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011964 for (i = 0; i < length; i++) {
11965 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011966 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011967 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011968 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969}
11970
INADA Naoki3ae20562017-01-16 20:41:20 +090011971/*[clinic input]
11972str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000011973
INADA Naoki3ae20562017-01-16 20:41:20 +090011974Return True if the string is a digit string, False otherwise.
11975
11976A string is a digit string if all characters in the string are digits and there
11977is at least one character in the string.
11978[clinic start generated code]*/
11979
11980static PyObject *
11981unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011982/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011984 Py_ssize_t i, length;
11985 int kind;
11986 void *data;
11987
11988 if (PyUnicode_READY(self) == -1)
11989 return NULL;
11990 length = PyUnicode_GET_LENGTH(self);
11991 kind = PyUnicode_KIND(self);
11992 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011993
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011995 if (length == 1) {
11996 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11997 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11998 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011999
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012000 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012002 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012003
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 for (i = 0; i < length; i++) {
12005 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012006 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012008 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012009}
12010
INADA Naoki3ae20562017-01-16 20:41:20 +090012011/*[clinic input]
12012str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013
INADA Naoki3ae20562017-01-16 20:41:20 +090012014Return True if the string is a numeric string, False otherwise.
12015
12016A string is numeric if all characters in the string are numeric and there is at
12017least one character in the string.
12018[clinic start generated code]*/
12019
12020static PyObject *
12021unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012022/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012023{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 Py_ssize_t i, length;
12025 int kind;
12026 void *data;
12027
12028 if (PyUnicode_READY(self) == -1)
12029 return NULL;
12030 length = PyUnicode_GET_LENGTH(self);
12031 kind = PyUnicode_KIND(self);
12032 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033
Guido van Rossumd57fd912000-03-10 22:53:23 +000012034 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012035 if (length == 1)
12036 return PyBool_FromLong(
12037 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012038
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012039 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012041 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012042
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012043 for (i = 0; i < length; i++) {
12044 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012045 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012047 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012048}
12049
Martin v. Löwis47383402007-08-15 07:32:56 +000012050int
12051PyUnicode_IsIdentifier(PyObject *self)
12052{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012053 int kind;
12054 void *data;
12055 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012056 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058 if (PyUnicode_READY(self) == -1) {
12059 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012060 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 }
12062
12063 /* Special case for empty strings */
12064 if (PyUnicode_GET_LENGTH(self) == 0)
12065 return 0;
12066 kind = PyUnicode_KIND(self);
12067 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012068
12069 /* PEP 3131 says that the first character must be in
12070 XID_Start and subsequent characters in XID_Continue,
12071 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012072 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012073 letters, digits, underscore). However, given the current
12074 definition of XID_Start and XID_Continue, it is sufficient
12075 to check just for these, except that _ must be allowed
12076 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012077 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012078 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012079 return 0;
12080
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012081 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012082 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012083 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012084 return 1;
12085}
12086
INADA Naoki3ae20562017-01-16 20:41:20 +090012087/*[clinic input]
12088str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012089
INADA Naoki3ae20562017-01-16 20:41:20 +090012090Return True if the string is a valid Python identifier, False otherwise.
12091
Sanyam Khuranaffc5a142018-10-08 12:23:32 +053012092Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012093such as "def" or "class".
INADA Naoki3ae20562017-01-16 20:41:20 +090012094[clinic start generated code]*/
12095
12096static PyObject *
12097unicode_isidentifier_impl(PyObject *self)
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012098/*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012099{
12100 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12101}
12102
INADA Naoki3ae20562017-01-16 20:41:20 +090012103/*[clinic input]
12104str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012105
INADA Naoki3ae20562017-01-16 20:41:20 +090012106Return True if the string is printable, False otherwise.
12107
12108A string is printable if all of its characters are considered printable in
12109repr() or if it is empty.
12110[clinic start generated code]*/
12111
12112static PyObject *
12113unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012114/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012115{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012116 Py_ssize_t i, length;
12117 int kind;
12118 void *data;
12119
12120 if (PyUnicode_READY(self) == -1)
12121 return NULL;
12122 length = PyUnicode_GET_LENGTH(self);
12123 kind = PyUnicode_KIND(self);
12124 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012125
12126 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127 if (length == 1)
12128 return PyBool_FromLong(
12129 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012130
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012131 for (i = 0; i < length; i++) {
12132 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012133 Py_RETURN_FALSE;
12134 }
12135 }
12136 Py_RETURN_TRUE;
12137}
12138
INADA Naoki3ae20562017-01-16 20:41:20 +090012139/*[clinic input]
12140str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141
INADA Naoki3ae20562017-01-16 20:41:20 +090012142 iterable: object
12143 /
12144
12145Concatenate any number of strings.
12146
Martin Panter91a88662017-01-24 00:30:06 +000012147The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012148The result is returned as a new string.
12149
12150Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12151[clinic start generated code]*/
12152
12153static PyObject *
12154unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012155/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156{
INADA Naoki3ae20562017-01-16 20:41:20 +090012157 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012158}
12159
Martin v. Löwis18e16552006-02-15 17:27:45 +000012160static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012161unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012162{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163 if (PyUnicode_READY(self) == -1)
12164 return -1;
12165 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166}
12167
INADA Naoki3ae20562017-01-16 20:41:20 +090012168/*[clinic input]
12169str.ljust as unicode_ljust
12170
12171 width: Py_ssize_t
12172 fillchar: Py_UCS4 = ' '
12173 /
12174
12175Return a left-justified string of length width.
12176
12177Padding is done using the specified fill character (default is a space).
12178[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
12180static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012181unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12182/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012184 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012185 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186
Victor Stinnerc4b49542011-12-11 22:44:26 +010012187 if (PyUnicode_GET_LENGTH(self) >= width)
12188 return unicode_result_unchanged(self);
12189
12190 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191}
12192
INADA Naoki3ae20562017-01-16 20:41:20 +090012193/*[clinic input]
12194str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195
INADA Naoki3ae20562017-01-16 20:41:20 +090012196Return a copy of the string converted to lowercase.
12197[clinic start generated code]*/
12198
12199static PyObject *
12200unicode_lower_impl(PyObject *self)
12201/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012203 if (PyUnicode_READY(self) == -1)
12204 return NULL;
12205 if (PyUnicode_IS_ASCII(self))
12206 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012207 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208}
12209
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012210#define LEFTSTRIP 0
12211#define RIGHTSTRIP 1
12212#define BOTHSTRIP 2
12213
12214/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012215static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012216
INADA Naoki3ae20562017-01-16 20:41:20 +090012217#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012218
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012219/* externally visible for str.strip(unicode) */
12220PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012221_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012222{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012223 void *data;
12224 int kind;
12225 Py_ssize_t i, j, len;
12226 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012227 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012229 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12230 return NULL;
12231
12232 kind = PyUnicode_KIND(self);
12233 data = PyUnicode_DATA(self);
12234 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012235 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12237 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012238 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012239
Benjamin Peterson14339b62009-01-31 16:36:08 +000012240 i = 0;
12241 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012242 while (i < len) {
12243 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12244 if (!BLOOM(sepmask, ch))
12245 break;
12246 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12247 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012248 i++;
12249 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012250 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012251
Benjamin Peterson14339b62009-01-31 16:36:08 +000012252 j = len;
12253 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012254 j--;
12255 while (j >= i) {
12256 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12257 if (!BLOOM(sepmask, ch))
12258 break;
12259 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12260 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012261 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012262 }
12263
Benjamin Peterson29060642009-01-31 22:14:21 +000012264 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012265 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012266
Victor Stinner7931d9a2011-11-04 00:22:48 +010012267 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012268}
12269
12270PyObject*
12271PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12272{
12273 unsigned char *data;
12274 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012275 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012276
Victor Stinnerde636f32011-10-01 03:55:54 +020012277 if (PyUnicode_READY(self) == -1)
12278 return NULL;
12279
Victor Stinner684d5fd2012-05-03 02:32:34 +020012280 length = PyUnicode_GET_LENGTH(self);
12281 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012282
Victor Stinner684d5fd2012-05-03 02:32:34 +020012283 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012284 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285
Victor Stinnerde636f32011-10-01 03:55:54 +020012286 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012287 PyErr_SetString(PyExc_IndexError, "string index out of range");
12288 return NULL;
12289 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012290 if (start >= length || end < start)
12291 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012292
Victor Stinner684d5fd2012-05-03 02:32:34 +020012293 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012294 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012295 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012296 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012297 }
12298 else {
12299 kind = PyUnicode_KIND(self);
12300 data = PyUnicode_1BYTE_DATA(self);
12301 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012302 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012303 length);
12304 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306
12307static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012308do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012309{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012310 Py_ssize_t len, i, j;
12311
12312 if (PyUnicode_READY(self) == -1)
12313 return NULL;
12314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012316
Victor Stinnercc7af722013-04-09 22:39:24 +020012317 if (PyUnicode_IS_ASCII(self)) {
12318 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12319
12320 i = 0;
12321 if (striptype != RIGHTSTRIP) {
12322 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012323 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012324 if (!_Py_ascii_whitespace[ch])
12325 break;
12326 i++;
12327 }
12328 }
12329
12330 j = len;
12331 if (striptype != LEFTSTRIP) {
12332 j--;
12333 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012334 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012335 if (!_Py_ascii_whitespace[ch])
12336 break;
12337 j--;
12338 }
12339 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012340 }
12341 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012342 else {
12343 int kind = PyUnicode_KIND(self);
12344 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012345
Victor Stinnercc7af722013-04-09 22:39:24 +020012346 i = 0;
12347 if (striptype != RIGHTSTRIP) {
12348 while (i < len) {
12349 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12350 if (!Py_UNICODE_ISSPACE(ch))
12351 break;
12352 i++;
12353 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012354 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012355
12356 j = len;
12357 if (striptype != LEFTSTRIP) {
12358 j--;
12359 while (j >= i) {
12360 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12361 if (!Py_UNICODE_ISSPACE(ch))
12362 break;
12363 j--;
12364 }
12365 j++;
12366 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012367 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012368
Victor Stinner7931d9a2011-11-04 00:22:48 +010012369 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012370}
12371
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012372
12373static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012374do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012375{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012376 if (sep != NULL && sep != Py_None) {
12377 if (PyUnicode_Check(sep))
12378 return _PyUnicode_XStrip(self, striptype, sep);
12379 else {
12380 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012381 "%s arg must be None or str",
12382 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012383 return NULL;
12384 }
12385 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012386
Benjamin Peterson14339b62009-01-31 16:36:08 +000012387 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012388}
12389
12390
INADA Naoki3ae20562017-01-16 20:41:20 +090012391/*[clinic input]
12392str.strip as unicode_strip
12393
12394 chars: object = None
12395 /
12396
Victor Stinner0c4a8282017-01-17 02:21:47 +010012397Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012398
12399If chars is given and not None, remove characters in chars instead.
12400[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012401
12402static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012403unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012404/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012405{
INADA Naoki3ae20562017-01-16 20:41:20 +090012406 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012407}
12408
12409
INADA Naoki3ae20562017-01-16 20:41:20 +090012410/*[clinic input]
12411str.lstrip as unicode_lstrip
12412
12413 chars: object = NULL
12414 /
12415
12416Return a copy of the string with leading whitespace removed.
12417
12418If chars is given and not None, remove characters in chars instead.
12419[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012420
12421static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012422unicode_lstrip_impl(PyObject *self, PyObject *chars)
12423/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012424{
INADA Naoki3ae20562017-01-16 20:41:20 +090012425 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012426}
12427
12428
INADA Naoki3ae20562017-01-16 20:41:20 +090012429/*[clinic input]
12430str.rstrip as unicode_rstrip
12431
12432 chars: object = NULL
12433 /
12434
12435Return a copy of the string with trailing whitespace removed.
12436
12437If chars is given and not None, remove characters in chars instead.
12438[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012439
12440static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012441unicode_rstrip_impl(PyObject *self, PyObject *chars)
12442/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012443{
INADA Naoki3ae20562017-01-16 20:41:20 +090012444 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012445}
12446
12447
Guido van Rossumd57fd912000-03-10 22:53:23 +000012448static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012449unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012450{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012451 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012452 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012453
Serhiy Storchaka05997252013-01-26 12:14:02 +020012454 if (len < 1)
12455 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012456
Victor Stinnerc4b49542011-12-11 22:44:26 +010012457 /* no repeat, return original string */
12458 if (len == 1)
12459 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012460
Benjamin Petersonbac79492012-01-14 13:34:47 -050012461 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012462 return NULL;
12463
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012464 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012465 PyErr_SetString(PyExc_OverflowError,
12466 "repeated string is too long");
12467 return NULL;
12468 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012469 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012470
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012471 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012472 if (!u)
12473 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012474 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012476 if (PyUnicode_GET_LENGTH(str) == 1) {
12477 const int kind = PyUnicode_KIND(str);
12478 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012479 if (kind == PyUnicode_1BYTE_KIND) {
12480 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012481 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012482 }
12483 else if (kind == PyUnicode_2BYTE_KIND) {
12484 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012485 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012486 ucs2[n] = fill_char;
12487 } else {
12488 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12489 assert(kind == PyUnicode_4BYTE_KIND);
12490 for (n = 0; n < len; ++n)
12491 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012492 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012493 }
12494 else {
12495 /* number of characters copied this far */
12496 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012497 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012498 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012499 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012500 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012501 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012502 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012503 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012504 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012505 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506 }
12507
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012508 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012509 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510}
12511
Alexander Belopolsky40018472011-02-26 01:02:56 +000012512PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012513PyUnicode_Replace(PyObject *str,
12514 PyObject *substr,
12515 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012516 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012517{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012518 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12519 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012520 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012521 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522}
12523
INADA Naoki3ae20562017-01-16 20:41:20 +090012524/*[clinic input]
12525str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012526
INADA Naoki3ae20562017-01-16 20:41:20 +090012527 old: unicode
12528 new: unicode
12529 count: Py_ssize_t = -1
12530 Maximum number of occurrences to replace.
12531 -1 (the default value) means replace all occurrences.
12532 /
12533
12534Return a copy with all occurrences of substring old replaced by new.
12535
12536If the optional argument count is given, only the first count occurrences are
12537replaced.
12538[clinic start generated code]*/
12539
12540static PyObject *
12541unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12542 Py_ssize_t count)
12543/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012544{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012545 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012546 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012547 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012548}
12549
Alexander Belopolsky40018472011-02-26 01:02:56 +000012550static PyObject *
12551unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012552{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012553 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012554 Py_ssize_t isize;
12555 Py_ssize_t osize, squote, dquote, i, o;
12556 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012557 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012558 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012560 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012561 return NULL;
12562
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012563 isize = PyUnicode_GET_LENGTH(unicode);
12564 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012566 /* Compute length of output, quote characters, and
12567 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012568 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012569 max = 127;
12570 squote = dquote = 0;
12571 ikind = PyUnicode_KIND(unicode);
12572 for (i = 0; i < isize; i++) {
12573 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012574 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012575 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012576 case '\'': squote++; break;
12577 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012579 incr = 2;
12580 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012581 default:
12582 /* Fast-path ASCII */
12583 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012584 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012586 ;
12587 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012589 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012590 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012592 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012594 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012595 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012596 if (osize > PY_SSIZE_T_MAX - incr) {
12597 PyErr_SetString(PyExc_OverflowError,
12598 "string is too long to generate repr");
12599 return NULL;
12600 }
12601 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012602 }
12603
12604 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012605 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012606 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012607 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012608 if (dquote)
12609 /* Both squote and dquote present. Use squote,
12610 and escape them */
12611 osize += squote;
12612 else
12613 quote = '"';
12614 }
Victor Stinner55c08782013-04-14 18:45:39 +020012615 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616
12617 repr = PyUnicode_New(osize, max);
12618 if (repr == NULL)
12619 return NULL;
12620 okind = PyUnicode_KIND(repr);
12621 odata = PyUnicode_DATA(repr);
12622
12623 PyUnicode_WRITE(okind, odata, 0, quote);
12624 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012625 if (unchanged) {
12626 _PyUnicode_FastCopyCharacters(repr, 1,
12627 unicode, 0,
12628 isize);
12629 }
12630 else {
12631 for (i = 0, o = 1; i < isize; i++) {
12632 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012633
Victor Stinner55c08782013-04-14 18:45:39 +020012634 /* Escape quotes and backslashes */
12635 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012636 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012637 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012638 continue;
12639 }
12640
12641 /* Map special whitespace to '\t', \n', '\r' */
12642 if (ch == '\t') {
12643 PyUnicode_WRITE(okind, odata, o++, '\\');
12644 PyUnicode_WRITE(okind, odata, o++, 't');
12645 }
12646 else if (ch == '\n') {
12647 PyUnicode_WRITE(okind, odata, o++, '\\');
12648 PyUnicode_WRITE(okind, odata, o++, 'n');
12649 }
12650 else if (ch == '\r') {
12651 PyUnicode_WRITE(okind, odata, o++, '\\');
12652 PyUnicode_WRITE(okind, odata, o++, 'r');
12653 }
12654
12655 /* Map non-printable US ASCII to '\xhh' */
12656 else if (ch < ' ' || ch == 0x7F) {
12657 PyUnicode_WRITE(okind, odata, o++, '\\');
12658 PyUnicode_WRITE(okind, odata, o++, 'x');
12659 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12660 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12661 }
12662
12663 /* Copy ASCII characters as-is */
12664 else if (ch < 0x7F) {
12665 PyUnicode_WRITE(okind, odata, o++, ch);
12666 }
12667
12668 /* Non-ASCII characters */
12669 else {
12670 /* Map Unicode whitespace and control characters
12671 (categories Z* and C* except ASCII space)
12672 */
12673 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12674 PyUnicode_WRITE(okind, odata, o++, '\\');
12675 /* Map 8-bit characters to '\xhh' */
12676 if (ch <= 0xff) {
12677 PyUnicode_WRITE(okind, odata, o++, 'x');
12678 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12679 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12680 }
12681 /* Map 16-bit characters to '\uxxxx' */
12682 else if (ch <= 0xffff) {
12683 PyUnicode_WRITE(okind, odata, o++, 'u');
12684 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12685 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12686 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12687 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12688 }
12689 /* Map 21-bit characters to '\U00xxxxxx' */
12690 else {
12691 PyUnicode_WRITE(okind, odata, o++, 'U');
12692 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12693 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12694 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12695 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12696 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12697 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12698 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12699 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12700 }
12701 }
12702 /* Copy characters as-is */
12703 else {
12704 PyUnicode_WRITE(okind, odata, o++, ch);
12705 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012706 }
12707 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012708 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012709 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012710 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012711 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712}
12713
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012714PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012715 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716\n\
12717Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012718such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719arguments start and end are interpreted as in slice notation.\n\
12720\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012721Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722
12723static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012724unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012725{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012726 /* initialize variables to prevent gcc warning */
12727 PyObject *substring = NULL;
12728 Py_ssize_t start = 0;
12729 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012730 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012731
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012732 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012733 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012734
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012735 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012737
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012738 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012739
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012740 if (result == -2)
12741 return NULL;
12742
Christian Heimes217cfd12007-12-02 14:31:20 +000012743 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744}
12745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012746PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012747 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012748\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012749Return the highest index in S where substring sub is found,\n\
12750such that sub is contained within S[start:end]. Optional\n\
12751arguments start and end are interpreted as in slice notation.\n\
12752\n\
12753Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754
12755static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012756unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012758 /* initialize variables to prevent gcc warning */
12759 PyObject *substring = NULL;
12760 Py_ssize_t start = 0;
12761 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012762 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012764 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012765 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012767 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012768 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012769
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012770 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012771
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012772 if (result == -2)
12773 return NULL;
12774
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775 if (result < 0) {
12776 PyErr_SetString(PyExc_ValueError, "substring not found");
12777 return NULL;
12778 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012779
Christian Heimes217cfd12007-12-02 14:31:20 +000012780 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781}
12782
INADA Naoki3ae20562017-01-16 20:41:20 +090012783/*[clinic input]
12784str.rjust as unicode_rjust
12785
12786 width: Py_ssize_t
12787 fillchar: Py_UCS4 = ' '
12788 /
12789
12790Return a right-justified string of length width.
12791
12792Padding is done using the specified fill character (default is a space).
12793[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794
12795static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012796unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12797/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012799 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800 return NULL;
12801
Victor Stinnerc4b49542011-12-11 22:44:26 +010012802 if (PyUnicode_GET_LENGTH(self) >= width)
12803 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804
Victor Stinnerc4b49542011-12-11 22:44:26 +010012805 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806}
12807
Alexander Belopolsky40018472011-02-26 01:02:56 +000012808PyObject *
12809PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012811 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012812 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012814 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012815}
12816
INADA Naoki3ae20562017-01-16 20:41:20 +090012817/*[clinic input]
12818str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819
INADA Naoki3ae20562017-01-16 20:41:20 +090012820 sep: object = None
12821 The delimiter according which to split the string.
12822 None (the default value) means split according to any whitespace,
12823 and discard empty strings from the result.
12824 maxsplit: Py_ssize_t = -1
12825 Maximum number of splits to do.
12826 -1 (the default value) means no limit.
12827
12828Return a list of the words in the string, using sep as the delimiter string.
12829[clinic start generated code]*/
12830
12831static PyObject *
12832unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12833/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834{
INADA Naoki3ae20562017-01-16 20:41:20 +090012835 if (sep == Py_None)
12836 return split(self, NULL, maxsplit);
12837 if (PyUnicode_Check(sep))
12838 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012839
Victor Stinner998b8062018-09-12 00:23:25 +020012840 PyErr_Format(PyExc_TypeError,
12841 "must be str or None, not %.100s",
12842 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012843 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844}
12845
Thomas Wouters477c8d52006-05-27 19:21:47 +000012846PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012847PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012848{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012849 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012850 int kind1, kind2;
12851 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012852 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012853
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012854 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012855 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012856
Victor Stinner14f8f022011-10-05 20:58:25 +020012857 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012859 len1 = PyUnicode_GET_LENGTH(str_obj);
12860 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012861 if (kind1 < kind2 || len1 < len2) {
12862 _Py_INCREF_UNICODE_EMPTY();
12863 if (!unicode_empty)
12864 out = NULL;
12865 else {
12866 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12867 Py_DECREF(unicode_empty);
12868 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012869 return out;
12870 }
12871 buf1 = PyUnicode_DATA(str_obj);
12872 buf2 = PyUnicode_DATA(sep_obj);
12873 if (kind2 != kind1) {
12874 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12875 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012876 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012878
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012879 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012880 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012881 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12882 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12883 else
12884 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885 break;
12886 case PyUnicode_2BYTE_KIND:
12887 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12888 break;
12889 case PyUnicode_4BYTE_KIND:
12890 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12891 break;
12892 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012893 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012894 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012895
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012896 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012897 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012898
12899 return out;
12900}
12901
12902
12903PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012904PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012905{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012906 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012907 int kind1, kind2;
12908 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012909 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012910
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012911 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012912 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012913
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012914 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012915 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012916 len1 = PyUnicode_GET_LENGTH(str_obj);
12917 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012918 if (kind1 < kind2 || len1 < len2) {
12919 _Py_INCREF_UNICODE_EMPTY();
12920 if (!unicode_empty)
12921 out = NULL;
12922 else {
12923 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
12924 Py_DECREF(unicode_empty);
12925 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012926 return out;
12927 }
12928 buf1 = PyUnicode_DATA(str_obj);
12929 buf2 = PyUnicode_DATA(sep_obj);
12930 if (kind2 != kind1) {
12931 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12932 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012933 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012934 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012935
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012936 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012937 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012938 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12939 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12940 else
12941 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012942 break;
12943 case PyUnicode_2BYTE_KIND:
12944 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12945 break;
12946 case PyUnicode_4BYTE_KIND:
12947 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12948 break;
12949 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012950 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012951 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012952
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012953 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012954 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012955
12956 return out;
12957}
12958
INADA Naoki3ae20562017-01-16 20:41:20 +090012959/*[clinic input]
12960str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012961
INADA Naoki3ae20562017-01-16 20:41:20 +090012962 sep: object
12963 /
12964
12965Partition the string into three parts using the given separator.
12966
12967This will search for the separator in the string. If the separator is found,
12968returns a 3-tuple containing the part before the separator, the separator
12969itself, and the part after it.
12970
12971If the separator is not found, returns a 3-tuple containing the original string
12972and two empty strings.
12973[clinic start generated code]*/
12974
12975static PyObject *
12976unicode_partition(PyObject *self, PyObject *sep)
12977/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012978{
INADA Naoki3ae20562017-01-16 20:41:20 +090012979 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012980}
12981
INADA Naoki3ae20562017-01-16 20:41:20 +090012982/*[clinic input]
12983str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000012984
INADA Naoki3ae20562017-01-16 20:41:20 +090012985Partition the string into three parts using the given separator.
12986
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012987This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090012988the separator is found, returns a 3-tuple containing the part before the
12989separator, the separator itself, and the part after it.
12990
12991If the separator is not found, returns a 3-tuple containing two empty strings
12992and the original string.
12993[clinic start generated code]*/
12994
12995static PyObject *
12996unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030012997/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000012998{
INADA Naoki3ae20562017-01-16 20:41:20 +090012999 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013000}
13001
Alexander Belopolsky40018472011-02-26 01:02:56 +000013002PyObject *
13003PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013004{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013005 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013006 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013007
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013008 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013009}
13010
INADA Naoki3ae20562017-01-16 20:41:20 +090013011/*[clinic input]
13012str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013013
INADA Naoki3ae20562017-01-16 20:41:20 +090013014Return a list of the words in the string, using sep as the delimiter string.
13015
13016Splits are done starting at the end of the string and working to the front.
13017[clinic start generated code]*/
13018
13019static PyObject *
13020unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13021/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013022{
INADA Naoki3ae20562017-01-16 20:41:20 +090013023 if (sep == Py_None)
13024 return rsplit(self, NULL, maxsplit);
13025 if (PyUnicode_Check(sep))
13026 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013027
Victor Stinner998b8062018-09-12 00:23:25 +020013028 PyErr_Format(PyExc_TypeError,
13029 "must be str or None, not %.100s",
13030 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013031 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013032}
13033
INADA Naoki3ae20562017-01-16 20:41:20 +090013034/*[clinic input]
13035str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013036
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013037 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013038
13039Return a list of the lines in the string, breaking at line boundaries.
13040
13041Line breaks are not included in the resulting list unless keepends is given and
13042true.
13043[clinic start generated code]*/
13044
13045static PyObject *
13046unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013047/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013048{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013049 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013050}
13051
13052static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013053PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013055 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056}
13057
INADA Naoki3ae20562017-01-16 20:41:20 +090013058/*[clinic input]
13059str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013060
INADA Naoki3ae20562017-01-16 20:41:20 +090013061Convert uppercase characters to lowercase and lowercase characters to uppercase.
13062[clinic start generated code]*/
13063
13064static PyObject *
13065unicode_swapcase_impl(PyObject *self)
13066/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013068 if (PyUnicode_READY(self) == -1)
13069 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013070 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071}
13072
Larry Hastings61272b72014-01-07 12:41:53 -080013073/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013074
Larry Hastings31826802013-10-19 00:09:25 -070013075@staticmethod
13076str.maketrans as unicode_maketrans
13077
13078 x: object
13079
13080 y: unicode=NULL
13081
13082 z: unicode=NULL
13083
13084 /
13085
13086Return a translation table usable for str.translate().
13087
13088If there is only one argument, it must be a dictionary mapping Unicode
13089ordinals (integers) or characters to Unicode ordinals, strings or None.
13090Character keys will be then converted to ordinals.
13091If there are two arguments, they must be strings of equal length, and
13092in the resulting dictionary, each character in x will be mapped to the
13093character at the same position in y. If there is a third argument, it
13094must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013095[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013096
Larry Hastings31826802013-10-19 00:09:25 -070013097static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013098unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013099/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013100{
Georg Brandlceee0772007-11-27 23:48:05 +000013101 PyObject *new = NULL, *key, *value;
13102 Py_ssize_t i = 0;
13103 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013104
Georg Brandlceee0772007-11-27 23:48:05 +000013105 new = PyDict_New();
13106 if (!new)
13107 return NULL;
13108 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013109 int x_kind, y_kind, z_kind;
13110 void *x_data, *y_data, *z_data;
13111
Georg Brandlceee0772007-11-27 23:48:05 +000013112 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013113 if (!PyUnicode_Check(x)) {
13114 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13115 "be a string if there is a second argument");
13116 goto err;
13117 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013118 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013119 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13120 "arguments must have equal length");
13121 goto err;
13122 }
13123 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013124 x_kind = PyUnicode_KIND(x);
13125 y_kind = PyUnicode_KIND(y);
13126 x_data = PyUnicode_DATA(x);
13127 y_data = PyUnicode_DATA(y);
13128 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13129 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013130 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013131 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013132 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013133 if (!value) {
13134 Py_DECREF(key);
13135 goto err;
13136 }
Georg Brandlceee0772007-11-27 23:48:05 +000013137 res = PyDict_SetItem(new, key, value);
13138 Py_DECREF(key);
13139 Py_DECREF(value);
13140 if (res < 0)
13141 goto err;
13142 }
13143 /* create entries for deleting chars in z */
13144 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013145 z_kind = PyUnicode_KIND(z);
13146 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013147 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013148 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013149 if (!key)
13150 goto err;
13151 res = PyDict_SetItem(new, key, Py_None);
13152 Py_DECREF(key);
13153 if (res < 0)
13154 goto err;
13155 }
13156 }
13157 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013158 int kind;
13159 void *data;
13160
Georg Brandlceee0772007-11-27 23:48:05 +000013161 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013162 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013163 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13164 "to maketrans it must be a dict");
13165 goto err;
13166 }
13167 /* copy entries into the new dict, converting string keys to int keys */
13168 while (PyDict_Next(x, &i, &key, &value)) {
13169 if (PyUnicode_Check(key)) {
13170 /* convert string keys to integer keys */
13171 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013172 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013173 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13174 "table must be of length 1");
13175 goto err;
13176 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013177 kind = PyUnicode_KIND(key);
13178 data = PyUnicode_DATA(key);
13179 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013180 if (!newkey)
13181 goto err;
13182 res = PyDict_SetItem(new, newkey, value);
13183 Py_DECREF(newkey);
13184 if (res < 0)
13185 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013186 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013187 /* just keep integer keys */
13188 if (PyDict_SetItem(new, key, value) < 0)
13189 goto err;
13190 } else {
13191 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13192 "be strings or integers");
13193 goto err;
13194 }
13195 }
13196 }
13197 return new;
13198 err:
13199 Py_DECREF(new);
13200 return NULL;
13201}
13202
INADA Naoki3ae20562017-01-16 20:41:20 +090013203/*[clinic input]
13204str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205
INADA Naoki3ae20562017-01-16 20:41:20 +090013206 table: object
13207 Translation table, which must be a mapping of Unicode ordinals to
13208 Unicode ordinals, strings, or None.
13209 /
13210
13211Replace each character in the string using the given translation table.
13212
13213The table must implement lookup/indexing via __getitem__, for instance a
13214dictionary or list. If this operation raises LookupError, the character is
13215left untouched. Characters mapped to None are deleted.
13216[clinic start generated code]*/
13217
13218static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013219unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013220/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013221{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013222 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013223}
13224
INADA Naoki3ae20562017-01-16 20:41:20 +090013225/*[clinic input]
13226str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013227
INADA Naoki3ae20562017-01-16 20:41:20 +090013228Return a copy of the string converted to uppercase.
13229[clinic start generated code]*/
13230
13231static PyObject *
13232unicode_upper_impl(PyObject *self)
13233/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013235 if (PyUnicode_READY(self) == -1)
13236 return NULL;
13237 if (PyUnicode_IS_ASCII(self))
13238 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013239 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240}
13241
INADA Naoki3ae20562017-01-16 20:41:20 +090013242/*[clinic input]
13243str.zfill as unicode_zfill
13244
13245 width: Py_ssize_t
13246 /
13247
13248Pad a numeric string with zeros on the left, to fill a field of the given width.
13249
13250The string is never truncated.
13251[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013252
13253static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013254unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013255/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013257 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013258 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013259 int kind;
13260 void *data;
13261 Py_UCS4 chr;
13262
Benjamin Petersonbac79492012-01-14 13:34:47 -050013263 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013264 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013265
Victor Stinnerc4b49542011-12-11 22:44:26 +010013266 if (PyUnicode_GET_LENGTH(self) >= width)
13267 return unicode_result_unchanged(self);
13268
13269 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013270
13271 u = pad(self, fill, 0, '0');
13272
Walter Dörwald068325e2002-04-15 13:36:47 +000013273 if (u == NULL)
13274 return NULL;
13275
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013276 kind = PyUnicode_KIND(u);
13277 data = PyUnicode_DATA(u);
13278 chr = PyUnicode_READ(kind, data, fill);
13279
13280 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013281 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013282 PyUnicode_WRITE(kind, data, 0, chr);
13283 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013284 }
13285
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013286 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013287 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013289
13290#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013291static PyObject *
13292unicode__decimal2ascii(PyObject *self)
13293{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013294 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013295}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013296#endif
13297
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013298PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013299 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013300\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013301Return True if S starts with the specified prefix, False otherwise.\n\
13302With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013303With optional end, stop comparing S at that position.\n\
13304prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013305
13306static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013307unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013308 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013309{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013310 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013311 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013312 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013313 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013314 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013315
Jesus Ceaac451502011-04-20 17:09:23 +020013316 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013317 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013318 if (PyTuple_Check(subobj)) {
13319 Py_ssize_t i;
13320 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013321 substring = PyTuple_GET_ITEM(subobj, i);
13322 if (!PyUnicode_Check(substring)) {
13323 PyErr_Format(PyExc_TypeError,
13324 "tuple for startswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013325 "not %.100s",
13326 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013327 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013328 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013329 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013330 if (result == -1)
13331 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013332 if (result) {
13333 Py_RETURN_TRUE;
13334 }
13335 }
13336 /* nothing matched */
13337 Py_RETURN_FALSE;
13338 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013339 if (!PyUnicode_Check(subobj)) {
13340 PyErr_Format(PyExc_TypeError,
13341 "startswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013342 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013343 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013344 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013345 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013346 if (result == -1)
13347 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013348 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013349}
13350
13351
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013352PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013353 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013355Return True if S ends with the specified suffix, False otherwise.\n\
13356With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013357With optional end, stop comparing S at that position.\n\
13358suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013359
13360static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013361unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013363{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013364 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013365 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013366 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013367 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013368 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013369
Jesus Ceaac451502011-04-20 17:09:23 +020013370 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013371 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013372 if (PyTuple_Check(subobj)) {
13373 Py_ssize_t i;
13374 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013375 substring = PyTuple_GET_ITEM(subobj, i);
13376 if (!PyUnicode_Check(substring)) {
13377 PyErr_Format(PyExc_TypeError,
13378 "tuple for endswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013379 "not %.100s",
13380 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013382 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013383 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013384 if (result == -1)
13385 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013386 if (result) {
13387 Py_RETURN_TRUE;
13388 }
13389 }
13390 Py_RETURN_FALSE;
13391 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013392 if (!PyUnicode_Check(subobj)) {
13393 PyErr_Format(PyExc_TypeError,
13394 "endswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013395 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013397 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013398 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013399 if (result == -1)
13400 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013401 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013402}
13403
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013404static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013405_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013406{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013407 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13408 writer->data = PyUnicode_DATA(writer->buffer);
13409
13410 if (!writer->readonly) {
13411 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013412 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013413 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013414 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013415 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13416 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13417 writer->kind = PyUnicode_WCHAR_KIND;
13418 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13419
Victor Stinner8f674cc2013-04-17 23:02:17 +020013420 /* Copy-on-write mode: set buffer size to 0 so
13421 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13422 * next write. */
13423 writer->size = 0;
13424 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013425}
13426
Victor Stinnerd3f08822012-05-29 12:57:52 +020013427void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013428_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013429{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013430 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013431
13432 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013433 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013434
13435 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13436 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13437 writer->kind = PyUnicode_WCHAR_KIND;
13438 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013439}
13440
Victor Stinnerd3f08822012-05-29 12:57:52 +020013441int
13442_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13443 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013444{
13445 Py_ssize_t newlen;
13446 PyObject *newbuffer;
13447
Victor Stinner2740e462016-09-06 16:58:36 -070013448 assert(maxchar <= MAX_UNICODE);
13449
Victor Stinnerca9381e2015-09-22 00:58:32 +020013450 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013451 assert((maxchar > writer->maxchar && length >= 0)
13452 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013453
Victor Stinner202fdca2012-05-07 12:47:02 +020013454 if (length > PY_SSIZE_T_MAX - writer->pos) {
13455 PyErr_NoMemory();
13456 return -1;
13457 }
13458 newlen = writer->pos + length;
13459
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013460 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013461
Victor Stinnerd3f08822012-05-29 12:57:52 +020013462 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013463 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013464 if (writer->overallocate
13465 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13466 /* overallocate to limit the number of realloc() */
13467 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013468 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013469 if (newlen < writer->min_length)
13470 newlen = writer->min_length;
13471
Victor Stinnerd3f08822012-05-29 12:57:52 +020013472 writer->buffer = PyUnicode_New(newlen, maxchar);
13473 if (writer->buffer == NULL)
13474 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013475 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013476 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013477 if (writer->overallocate
13478 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13479 /* overallocate to limit the number of realloc() */
13480 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013481 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013482 if (newlen < writer->min_length)
13483 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013484
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013485 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013486 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013487 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013488 newbuffer = PyUnicode_New(newlen, maxchar);
13489 if (newbuffer == NULL)
13490 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013491 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13492 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013493 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013494 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013495 }
13496 else {
13497 newbuffer = resize_compact(writer->buffer, newlen);
13498 if (newbuffer == NULL)
13499 return -1;
13500 }
13501 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013502 }
13503 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013504 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013505 newbuffer = PyUnicode_New(writer->size, maxchar);
13506 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013507 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013508 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13509 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013510 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013511 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013512 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013513 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013514
13515#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013516}
13517
Victor Stinnerca9381e2015-09-22 00:58:32 +020013518int
13519_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13520 enum PyUnicode_Kind kind)
13521{
13522 Py_UCS4 maxchar;
13523
13524 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13525 assert(writer->kind < kind);
13526
13527 switch (kind)
13528 {
13529 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13530 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13531 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13532 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013533 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013534 }
13535
13536 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13537}
13538
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013539static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013540_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013541{
Victor Stinner2740e462016-09-06 16:58:36 -070013542 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013543 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13544 return -1;
13545 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13546 writer->pos++;
13547 return 0;
13548}
13549
13550int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013551_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13552{
13553 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13554}
13555
13556int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013557_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13558{
13559 Py_UCS4 maxchar;
13560 Py_ssize_t len;
13561
13562 if (PyUnicode_READY(str) == -1)
13563 return -1;
13564 len = PyUnicode_GET_LENGTH(str);
13565 if (len == 0)
13566 return 0;
13567 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13568 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013569 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013570 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013571 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013572 Py_INCREF(str);
13573 writer->buffer = str;
13574 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013575 writer->pos += len;
13576 return 0;
13577 }
13578 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13579 return -1;
13580 }
13581 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13582 str, 0, len);
13583 writer->pos += len;
13584 return 0;
13585}
13586
Victor Stinnere215d962012-10-06 23:03:36 +020013587int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013588_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13589 Py_ssize_t start, Py_ssize_t end)
13590{
13591 Py_UCS4 maxchar;
13592 Py_ssize_t len;
13593
13594 if (PyUnicode_READY(str) == -1)
13595 return -1;
13596
13597 assert(0 <= start);
13598 assert(end <= PyUnicode_GET_LENGTH(str));
13599 assert(start <= end);
13600
13601 if (end == 0)
13602 return 0;
13603
13604 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13605 return _PyUnicodeWriter_WriteStr(writer, str);
13606
13607 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13608 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13609 else
13610 maxchar = writer->maxchar;
13611 len = end - start;
13612
13613 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13614 return -1;
13615
13616 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13617 str, start, len);
13618 writer->pos += len;
13619 return 0;
13620}
13621
13622int
Victor Stinner4a587072013-11-19 12:54:53 +010013623_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13624 const char *ascii, Py_ssize_t len)
13625{
13626 if (len == -1)
13627 len = strlen(ascii);
13628
13629 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13630
13631 if (writer->buffer == NULL && !writer->overallocate) {
13632 PyObject *str;
13633
13634 str = _PyUnicode_FromASCII(ascii, len);
13635 if (str == NULL)
13636 return -1;
13637
13638 writer->readonly = 1;
13639 writer->buffer = str;
13640 _PyUnicodeWriter_Update(writer);
13641 writer->pos += len;
13642 return 0;
13643 }
13644
13645 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13646 return -1;
13647
13648 switch (writer->kind)
13649 {
13650 case PyUnicode_1BYTE_KIND:
13651 {
13652 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13653 Py_UCS1 *data = writer->data;
13654
Christian Heimesf051e432016-09-13 20:22:02 +020013655 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013656 break;
13657 }
13658 case PyUnicode_2BYTE_KIND:
13659 {
13660 _PyUnicode_CONVERT_BYTES(
13661 Py_UCS1, Py_UCS2,
13662 ascii, ascii + len,
13663 (Py_UCS2 *)writer->data + writer->pos);
13664 break;
13665 }
13666 case PyUnicode_4BYTE_KIND:
13667 {
13668 _PyUnicode_CONVERT_BYTES(
13669 Py_UCS1, Py_UCS4,
13670 ascii, ascii + len,
13671 (Py_UCS4 *)writer->data + writer->pos);
13672 break;
13673 }
13674 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013675 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013676 }
13677
13678 writer->pos += len;
13679 return 0;
13680}
13681
13682int
13683_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13684 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013685{
13686 Py_UCS4 maxchar;
13687
13688 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13689 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13690 return -1;
13691 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13692 writer->pos += len;
13693 return 0;
13694}
13695
Victor Stinnerd3f08822012-05-29 12:57:52 +020013696PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013697_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013698{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013699 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013700
Victor Stinnerd3f08822012-05-29 12:57:52 +020013701 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013702 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013703 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013704 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013705
13706 str = writer->buffer;
13707 writer->buffer = NULL;
13708
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013709 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013710 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13711 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013712 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013713
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013714 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13715 PyObject *str2;
13716 str2 = resize_compact(str, writer->pos);
13717 if (str2 == NULL) {
13718 Py_DECREF(str);
13719 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013720 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013721 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013722 }
13723
Victor Stinner15a0bd32013-07-08 22:29:55 +020013724 assert(_PyUnicode_CheckConsistency(str, 1));
13725 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013726}
13727
Victor Stinnerd3f08822012-05-29 12:57:52 +020013728void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013729_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013730{
13731 Py_CLEAR(writer->buffer);
13732}
13733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013734#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013735
13736PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013737 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013738\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013739Return a formatted version of S, using substitutions from args and kwargs.\n\
13740The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013741
Eric Smith27bbca62010-11-04 17:06:58 +000013742PyDoc_STRVAR(format_map__doc__,
13743 "S.format_map(mapping) -> str\n\
13744\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013745Return a formatted version of S, using substitutions from mapping.\n\
13746The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013747
INADA Naoki3ae20562017-01-16 20:41:20 +090013748/*[clinic input]
13749str.__format__ as unicode___format__
13750
13751 format_spec: unicode
13752 /
13753
13754Return a formatted version of the string as described by format_spec.
13755[clinic start generated code]*/
13756
Eric Smith4a7d76d2008-05-30 18:10:19 +000013757static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013758unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013759/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013760{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013761 _PyUnicodeWriter writer;
13762 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013763
Victor Stinnerd3f08822012-05-29 12:57:52 +020013764 if (PyUnicode_READY(self) == -1)
13765 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013766 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013767 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13768 self, format_spec, 0,
13769 PyUnicode_GET_LENGTH(format_spec));
13770 if (ret == -1) {
13771 _PyUnicodeWriter_Dealloc(&writer);
13772 return NULL;
13773 }
13774 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013775}
13776
INADA Naoki3ae20562017-01-16 20:41:20 +090013777/*[clinic input]
13778str.__sizeof__ as unicode_sizeof
13779
13780Return the size of the string in memory, in bytes.
13781[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013782
13783static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013784unicode_sizeof_impl(PyObject *self)
13785/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013786{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013787 Py_ssize_t size;
13788
13789 /* If it's a compact object, account for base structure +
13790 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013791 if (PyUnicode_IS_COMPACT_ASCII(self))
13792 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13793 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013794 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013795 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013796 else {
13797 /* If it is a two-block object, account for base object, and
13798 for character block if present. */
13799 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013800 if (_PyUnicode_DATA_ANY(self))
13801 size += (PyUnicode_GET_LENGTH(self) + 1) *
13802 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013803 }
13804 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013805 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013806 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13807 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13808 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13809 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013810
13811 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013812}
13813
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013814static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013815unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013816{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013817 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013818 if (!copy)
13819 return NULL;
13820 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013821}
13822
Guido van Rossumd57fd912000-03-10 22:53:23 +000013823static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013824 UNICODE_ENCODE_METHODDEF
13825 UNICODE_REPLACE_METHODDEF
13826 UNICODE_SPLIT_METHODDEF
13827 UNICODE_RSPLIT_METHODDEF
13828 UNICODE_JOIN_METHODDEF
13829 UNICODE_CAPITALIZE_METHODDEF
13830 UNICODE_CASEFOLD_METHODDEF
13831 UNICODE_TITLE_METHODDEF
13832 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013833 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013834 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013835 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013836 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013837 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013838 UNICODE_LJUST_METHODDEF
13839 UNICODE_LOWER_METHODDEF
13840 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013841 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13842 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013843 UNICODE_RJUST_METHODDEF
13844 UNICODE_RSTRIP_METHODDEF
13845 UNICODE_RPARTITION_METHODDEF
13846 UNICODE_SPLITLINES_METHODDEF
13847 UNICODE_STRIP_METHODDEF
13848 UNICODE_SWAPCASE_METHODDEF
13849 UNICODE_TRANSLATE_METHODDEF
13850 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013851 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13852 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013853 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013854 UNICODE_ISLOWER_METHODDEF
13855 UNICODE_ISUPPER_METHODDEF
13856 UNICODE_ISTITLE_METHODDEF
13857 UNICODE_ISSPACE_METHODDEF
13858 UNICODE_ISDECIMAL_METHODDEF
13859 UNICODE_ISDIGIT_METHODDEF
13860 UNICODE_ISNUMERIC_METHODDEF
13861 UNICODE_ISALPHA_METHODDEF
13862 UNICODE_ISALNUM_METHODDEF
13863 UNICODE_ISIDENTIFIER_METHODDEF
13864 UNICODE_ISPRINTABLE_METHODDEF
13865 UNICODE_ZFILL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013866 {"format", (PyCFunction)(void(*)(void)) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013867 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013868 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013869 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013870 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013871#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013872 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013873 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013874#endif
13875
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013876 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013877 {NULL, NULL}
13878};
13879
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013880static PyObject *
13881unicode_mod(PyObject *v, PyObject *w)
13882{
Brian Curtindfc80e32011-08-10 20:28:54 -050013883 if (!PyUnicode_Check(v))
13884 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013885 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013886}
13887
13888static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013889 0, /*nb_add*/
13890 0, /*nb_subtract*/
13891 0, /*nb_multiply*/
13892 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013893};
13894
Guido van Rossumd57fd912000-03-10 22:53:23 +000013895static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013896 (lenfunc) unicode_length, /* sq_length */
13897 PyUnicode_Concat, /* sq_concat */
13898 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13899 (ssizeargfunc) unicode_getitem, /* sq_item */
13900 0, /* sq_slice */
13901 0, /* sq_ass_item */
13902 0, /* sq_ass_slice */
13903 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013904};
13905
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013906static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013907unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013909 if (PyUnicode_READY(self) == -1)
13910 return NULL;
13911
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013912 if (PyIndex_Check(item)) {
13913 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013914 if (i == -1 && PyErr_Occurred())
13915 return NULL;
13916 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013917 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013918 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013919 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013920 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013921 PyObject *result;
13922 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013923 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013924 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013925
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013926 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013927 return NULL;
13928 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030013929 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
13930 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013931
13932 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020013933 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013934 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010013935 slicelength == PyUnicode_GET_LENGTH(self)) {
13936 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000013937 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013938 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013939 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013940 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013941 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013942 src_kind = PyUnicode_KIND(self);
13943 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013944 if (!PyUnicode_IS_ASCII(self)) {
13945 kind_limit = kind_maxchar_limit(src_kind);
13946 max_char = 0;
13947 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13948 ch = PyUnicode_READ(src_kind, src_data, cur);
13949 if (ch > max_char) {
13950 max_char = ch;
13951 if (max_char >= kind_limit)
13952 break;
13953 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013954 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013955 }
Victor Stinner55c99112011-10-13 01:17:06 +020013956 else
13957 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013958 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013959 if (result == NULL)
13960 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013961 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013962 dest_data = PyUnicode_DATA(result);
13963
13964 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013965 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13966 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013967 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013968 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013969 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013970 } else {
13971 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13972 return NULL;
13973 }
13974}
13975
13976static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013977 (lenfunc)unicode_length, /* mp_length */
13978 (binaryfunc)unicode_subscript, /* mp_subscript */
13979 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013980};
13981
Guido van Rossumd57fd912000-03-10 22:53:23 +000013982
Guido van Rossumd57fd912000-03-10 22:53:23 +000013983/* Helpers for PyUnicode_Format() */
13984
Victor Stinnera47082312012-10-04 02:19:54 +020013985struct unicode_formatter_t {
13986 PyObject *args;
13987 int args_owned;
13988 Py_ssize_t arglen, argidx;
13989 PyObject *dict;
13990
13991 enum PyUnicode_Kind fmtkind;
13992 Py_ssize_t fmtcnt, fmtpos;
13993 void *fmtdata;
13994 PyObject *fmtstr;
13995
13996 _PyUnicodeWriter writer;
13997};
13998
13999struct unicode_format_arg_t {
14000 Py_UCS4 ch;
14001 int flags;
14002 Py_ssize_t width;
14003 int prec;
14004 int sign;
14005};
14006
Guido van Rossumd57fd912000-03-10 22:53:23 +000014007static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014008unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014009{
Victor Stinnera47082312012-10-04 02:19:54 +020014010 Py_ssize_t argidx = ctx->argidx;
14011
14012 if (argidx < ctx->arglen) {
14013 ctx->argidx++;
14014 if (ctx->arglen < 0)
14015 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014016 else
Victor Stinnera47082312012-10-04 02:19:54 +020014017 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014018 }
14019 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014020 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014021 return NULL;
14022}
14023
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014024/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014025
Victor Stinnera47082312012-10-04 02:19:54 +020014026/* Format a float into the writer if the writer is not NULL, or into *p_output
14027 otherwise.
14028
14029 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014030static int
Victor Stinnera47082312012-10-04 02:19:54 +020014031formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14032 PyObject **p_output,
14033 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014034{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014035 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014036 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014037 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014038 int prec;
14039 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014040
Guido van Rossumd57fd912000-03-10 22:53:23 +000014041 x = PyFloat_AsDouble(v);
14042 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014043 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014044
Victor Stinnera47082312012-10-04 02:19:54 +020014045 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014046 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014047 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014048
Victor Stinnera47082312012-10-04 02:19:54 +020014049 if (arg->flags & F_ALT)
14050 dtoa_flags = Py_DTSF_ALT;
14051 else
14052 dtoa_flags = 0;
14053 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014054 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014055 return -1;
14056 len = strlen(p);
14057 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014058 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014059 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014060 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014061 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014062 }
14063 else
14064 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014065 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014066 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014067}
14068
Victor Stinnerd0880d52012-04-27 23:40:13 +020014069/* formatlong() emulates the format codes d, u, o, x and X, and
14070 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14071 * Python's regular ints.
14072 * Return value: a new PyUnicodeObject*, or NULL if error.
14073 * The output string is of the form
14074 * "-"? ("0x" | "0X")? digit+
14075 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14076 * set in flags. The case of hex digits will be correct,
14077 * There will be at least prec digits, zero-filled on the left if
14078 * necessary to get that many.
14079 * val object to be converted
14080 * flags bitmask of format flags; only F_ALT is looked at
14081 * prec minimum number of digits; 0-fill on left if needed
14082 * type a character in [duoxX]; u acts the same as d
14083 *
14084 * CAUTION: o, x and X conversions on regular ints can never
14085 * produce a '-' sign, but can for Python's unbounded ints.
14086 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014087PyObject *
14088_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014089{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014090 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014091 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014092 Py_ssize_t i;
14093 int sign; /* 1 if '-', else 0 */
14094 int len; /* number of characters */
14095 Py_ssize_t llen;
14096 int numdigits; /* len == numnondigits + numdigits */
14097 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014098
Victor Stinnerd0880d52012-04-27 23:40:13 +020014099 /* Avoid exceeding SSIZE_T_MAX */
14100 if (prec > INT_MAX-3) {
14101 PyErr_SetString(PyExc_OverflowError,
14102 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014103 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014104 }
14105
14106 assert(PyLong_Check(val));
14107
14108 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014109 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014110 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014111 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014112 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014113 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014114 /* int and int subclasses should print numerically when a numeric */
14115 /* format code is used (see issue18780) */
14116 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014117 break;
14118 case 'o':
14119 numnondigits = 2;
14120 result = PyNumber_ToBase(val, 8);
14121 break;
14122 case 'x':
14123 case 'X':
14124 numnondigits = 2;
14125 result = PyNumber_ToBase(val, 16);
14126 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014127 }
14128 if (!result)
14129 return NULL;
14130
14131 assert(unicode_modifiable(result));
14132 assert(PyUnicode_IS_READY(result));
14133 assert(PyUnicode_IS_ASCII(result));
14134
14135 /* To modify the string in-place, there can only be one reference. */
14136 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014137 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014138 PyErr_BadInternalCall();
14139 return NULL;
14140 }
14141 buf = PyUnicode_DATA(result);
14142 llen = PyUnicode_GET_LENGTH(result);
14143 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014144 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014145 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014146 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014147 return NULL;
14148 }
14149 len = (int)llen;
14150 sign = buf[0] == '-';
14151 numnondigits += sign;
14152 numdigits = len - numnondigits;
14153 assert(numdigits > 0);
14154
14155 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014156 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014157 (type == 'o' || type == 'x' || type == 'X'))) {
14158 assert(buf[sign] == '0');
14159 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14160 buf[sign+1] == 'o');
14161 numnondigits -= 2;
14162 buf += 2;
14163 len -= 2;
14164 if (sign)
14165 buf[0] = '-';
14166 assert(len == numnondigits + numdigits);
14167 assert(numdigits > 0);
14168 }
14169
14170 /* Fill with leading zeroes to meet minimum width. */
14171 if (prec > numdigits) {
14172 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14173 numnondigits + prec);
14174 char *b1;
14175 if (!r1) {
14176 Py_DECREF(result);
14177 return NULL;
14178 }
14179 b1 = PyBytes_AS_STRING(r1);
14180 for (i = 0; i < numnondigits; ++i)
14181 *b1++ = *buf++;
14182 for (i = 0; i < prec - numdigits; i++)
14183 *b1++ = '0';
14184 for (i = 0; i < numdigits; i++)
14185 *b1++ = *buf++;
14186 *b1 = '\0';
14187 Py_DECREF(result);
14188 result = r1;
14189 buf = PyBytes_AS_STRING(result);
14190 len = numnondigits + prec;
14191 }
14192
14193 /* Fix up case for hex conversions. */
14194 if (type == 'X') {
14195 /* Need to convert all lower case letters to upper case.
14196 and need to convert 0x to 0X (and -0x to -0X). */
14197 for (i = 0; i < len; i++)
14198 if (buf[i] >= 'a' && buf[i] <= 'x')
14199 buf[i] -= 'a'-'A';
14200 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014201 if (!PyUnicode_Check(result)
14202 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014203 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014204 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014205 Py_DECREF(result);
14206 result = unicode;
14207 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014208 else if (len != PyUnicode_GET_LENGTH(result)) {
14209 if (PyUnicode_Resize(&result, len) < 0)
14210 Py_CLEAR(result);
14211 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014212 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014213}
14214
Ethan Furmandf3ed242014-01-05 06:50:30 -080014215/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014216 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014217 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014218 * -1 and raise an exception on error */
14219static int
Victor Stinnera47082312012-10-04 02:19:54 +020014220mainformatlong(PyObject *v,
14221 struct unicode_format_arg_t *arg,
14222 PyObject **p_output,
14223 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014224{
14225 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014226 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014227
14228 if (!PyNumber_Check(v))
14229 goto wrongtype;
14230
Ethan Furman9ab74802014-03-21 06:38:46 -070014231 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014232 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014233 if (type == 'o' || type == 'x' || type == 'X') {
14234 iobj = PyNumber_Index(v);
14235 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014236 if (PyErr_ExceptionMatches(PyExc_TypeError))
14237 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014238 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014239 }
14240 }
14241 else {
14242 iobj = PyNumber_Long(v);
14243 if (iobj == NULL ) {
14244 if (PyErr_ExceptionMatches(PyExc_TypeError))
14245 goto wrongtype;
14246 return -1;
14247 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014248 }
14249 assert(PyLong_Check(iobj));
14250 }
14251 else {
14252 iobj = v;
14253 Py_INCREF(iobj);
14254 }
14255
14256 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014257 && arg->width == -1 && arg->prec == -1
14258 && !(arg->flags & (F_SIGN | F_BLANK))
14259 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014260 {
14261 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014262 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014263 int base;
14264
Victor Stinnera47082312012-10-04 02:19:54 +020014265 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014266 {
14267 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014268 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014269 case 'd':
14270 case 'i':
14271 case 'u':
14272 base = 10;
14273 break;
14274 case 'o':
14275 base = 8;
14276 break;
14277 case 'x':
14278 case 'X':
14279 base = 16;
14280 break;
14281 }
14282
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014283 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14284 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014285 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014286 }
14287 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014288 return 1;
14289 }
14290
Ethan Furmanb95b5612015-01-23 20:05:18 -080014291 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014292 Py_DECREF(iobj);
14293 if (res == NULL)
14294 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014295 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014296 return 0;
14297
14298wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014299 switch(type)
14300 {
14301 case 'o':
14302 case 'x':
14303 case 'X':
14304 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014305 "%%%c format: an integer is required, "
14306 "not %.200s",
14307 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014308 break;
14309 default:
14310 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014311 "%%%c format: a number is required, "
14312 "not %.200s",
14313 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014314 break;
14315 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014316 return -1;
14317}
14318
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014319static Py_UCS4
14320formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014321{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014322 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014323 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014324 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014325 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014326 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014327 goto onError;
14328 }
14329 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014330 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014331 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014332 /* make sure number is a type of integer */
14333 if (!PyLong_Check(v)) {
14334 iobj = PyNumber_Index(v);
14335 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014336 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014337 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014338 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014339 Py_DECREF(iobj);
14340 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014341 else {
14342 x = PyLong_AsLong(v);
14343 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014344 if (x == -1 && PyErr_Occurred())
14345 goto onError;
14346
Victor Stinner8faf8212011-12-08 22:14:11 +010014347 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014348 PyErr_SetString(PyExc_OverflowError,
14349 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014350 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014351 }
14352
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014353 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014354 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014355
Benjamin Peterson29060642009-01-31 22:14:21 +000014356 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014357 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014358 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014359 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014360}
14361
Victor Stinnera47082312012-10-04 02:19:54 +020014362/* Parse options of an argument: flags, width, precision.
14363 Handle also "%(name)" syntax.
14364
14365 Return 0 if the argument has been formatted into arg->str.
14366 Return 1 if the argument has been written into ctx->writer,
14367 Raise an exception and return -1 on error. */
14368static int
14369unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14370 struct unicode_format_arg_t *arg)
14371{
14372#define FORMAT_READ(ctx) \
14373 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14374
14375 PyObject *v;
14376
Victor Stinnera47082312012-10-04 02:19:54 +020014377 if (arg->ch == '(') {
14378 /* Get argument value from a dictionary. Example: "%(name)s". */
14379 Py_ssize_t keystart;
14380 Py_ssize_t keylen;
14381 PyObject *key;
14382 int pcount = 1;
14383
14384 if (ctx->dict == NULL) {
14385 PyErr_SetString(PyExc_TypeError,
14386 "format requires a mapping");
14387 return -1;
14388 }
14389 ++ctx->fmtpos;
14390 --ctx->fmtcnt;
14391 keystart = ctx->fmtpos;
14392 /* Skip over balanced parentheses */
14393 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14394 arg->ch = FORMAT_READ(ctx);
14395 if (arg->ch == ')')
14396 --pcount;
14397 else if (arg->ch == '(')
14398 ++pcount;
14399 ctx->fmtpos++;
14400 }
14401 keylen = ctx->fmtpos - keystart - 1;
14402 if (ctx->fmtcnt < 0 || pcount > 0) {
14403 PyErr_SetString(PyExc_ValueError,
14404 "incomplete format key");
14405 return -1;
14406 }
14407 key = PyUnicode_Substring(ctx->fmtstr,
14408 keystart, keystart + keylen);
14409 if (key == NULL)
14410 return -1;
14411 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014412 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014413 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014414 }
14415 ctx->args = PyObject_GetItem(ctx->dict, key);
14416 Py_DECREF(key);
14417 if (ctx->args == NULL)
14418 return -1;
14419 ctx->args_owned = 1;
14420 ctx->arglen = -1;
14421 ctx->argidx = -2;
14422 }
14423
14424 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014425 while (--ctx->fmtcnt >= 0) {
14426 arg->ch = FORMAT_READ(ctx);
14427 ctx->fmtpos++;
14428 switch (arg->ch) {
14429 case '-': arg->flags |= F_LJUST; continue;
14430 case '+': arg->flags |= F_SIGN; continue;
14431 case ' ': arg->flags |= F_BLANK; continue;
14432 case '#': arg->flags |= F_ALT; continue;
14433 case '0': arg->flags |= F_ZERO; continue;
14434 }
14435 break;
14436 }
14437
14438 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014439 if (arg->ch == '*') {
14440 v = unicode_format_getnextarg(ctx);
14441 if (v == NULL)
14442 return -1;
14443 if (!PyLong_Check(v)) {
14444 PyErr_SetString(PyExc_TypeError,
14445 "* wants int");
14446 return -1;
14447 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014448 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014449 if (arg->width == -1 && PyErr_Occurred())
14450 return -1;
14451 if (arg->width < 0) {
14452 arg->flags |= F_LJUST;
14453 arg->width = -arg->width;
14454 }
14455 if (--ctx->fmtcnt >= 0) {
14456 arg->ch = FORMAT_READ(ctx);
14457 ctx->fmtpos++;
14458 }
14459 }
14460 else if (arg->ch >= '0' && arg->ch <= '9') {
14461 arg->width = arg->ch - '0';
14462 while (--ctx->fmtcnt >= 0) {
14463 arg->ch = FORMAT_READ(ctx);
14464 ctx->fmtpos++;
14465 if (arg->ch < '0' || arg->ch > '9')
14466 break;
14467 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14468 mixing signed and unsigned comparison. Since arg->ch is between
14469 '0' and '9', casting to int is safe. */
14470 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14471 PyErr_SetString(PyExc_ValueError,
14472 "width too big");
14473 return -1;
14474 }
14475 arg->width = arg->width*10 + (arg->ch - '0');
14476 }
14477 }
14478
14479 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014480 if (arg->ch == '.') {
14481 arg->prec = 0;
14482 if (--ctx->fmtcnt >= 0) {
14483 arg->ch = FORMAT_READ(ctx);
14484 ctx->fmtpos++;
14485 }
14486 if (arg->ch == '*') {
14487 v = unicode_format_getnextarg(ctx);
14488 if (v == NULL)
14489 return -1;
14490 if (!PyLong_Check(v)) {
14491 PyErr_SetString(PyExc_TypeError,
14492 "* wants int");
14493 return -1;
14494 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014495 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014496 if (arg->prec == -1 && PyErr_Occurred())
14497 return -1;
14498 if (arg->prec < 0)
14499 arg->prec = 0;
14500 if (--ctx->fmtcnt >= 0) {
14501 arg->ch = FORMAT_READ(ctx);
14502 ctx->fmtpos++;
14503 }
14504 }
14505 else if (arg->ch >= '0' && arg->ch <= '9') {
14506 arg->prec = arg->ch - '0';
14507 while (--ctx->fmtcnt >= 0) {
14508 arg->ch = FORMAT_READ(ctx);
14509 ctx->fmtpos++;
14510 if (arg->ch < '0' || arg->ch > '9')
14511 break;
14512 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14513 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014514 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014515 return -1;
14516 }
14517 arg->prec = arg->prec*10 + (arg->ch - '0');
14518 }
14519 }
14520 }
14521
14522 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14523 if (ctx->fmtcnt >= 0) {
14524 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14525 if (--ctx->fmtcnt >= 0) {
14526 arg->ch = FORMAT_READ(ctx);
14527 ctx->fmtpos++;
14528 }
14529 }
14530 }
14531 if (ctx->fmtcnt < 0) {
14532 PyErr_SetString(PyExc_ValueError,
14533 "incomplete format");
14534 return -1;
14535 }
14536 return 0;
14537
14538#undef FORMAT_READ
14539}
14540
14541/* Format one argument. Supported conversion specifiers:
14542
14543 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014544 - "i", "d", "u": int or float
14545 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014546 - "e", "E", "f", "F", "g", "G": float
14547 - "c": int or str (1 character)
14548
Victor Stinner8dbd4212012-12-04 09:30:24 +010014549 When possible, the output is written directly into the Unicode writer
14550 (ctx->writer). A string is created when padding is required.
14551
Victor Stinnera47082312012-10-04 02:19:54 +020014552 Return 0 if the argument has been formatted into *p_str,
14553 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014554 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014555static int
14556unicode_format_arg_format(struct unicode_formatter_t *ctx,
14557 struct unicode_format_arg_t *arg,
14558 PyObject **p_str)
14559{
14560 PyObject *v;
14561 _PyUnicodeWriter *writer = &ctx->writer;
14562
14563 if (ctx->fmtcnt == 0)
14564 ctx->writer.overallocate = 0;
14565
Victor Stinnera47082312012-10-04 02:19:54 +020014566 v = unicode_format_getnextarg(ctx);
14567 if (v == NULL)
14568 return -1;
14569
Victor Stinnera47082312012-10-04 02:19:54 +020014570
14571 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014572 case 's':
14573 case 'r':
14574 case 'a':
14575 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14576 /* Fast path */
14577 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14578 return -1;
14579 return 1;
14580 }
14581
14582 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14583 *p_str = v;
14584 Py_INCREF(*p_str);
14585 }
14586 else {
14587 if (arg->ch == 's')
14588 *p_str = PyObject_Str(v);
14589 else if (arg->ch == 'r')
14590 *p_str = PyObject_Repr(v);
14591 else
14592 *p_str = PyObject_ASCII(v);
14593 }
14594 break;
14595
14596 case 'i':
14597 case 'd':
14598 case 'u':
14599 case 'o':
14600 case 'x':
14601 case 'X':
14602 {
14603 int ret = mainformatlong(v, arg, p_str, writer);
14604 if (ret != 0)
14605 return ret;
14606 arg->sign = 1;
14607 break;
14608 }
14609
14610 case 'e':
14611 case 'E':
14612 case 'f':
14613 case 'F':
14614 case 'g':
14615 case 'G':
14616 if (arg->width == -1 && arg->prec == -1
14617 && !(arg->flags & (F_SIGN | F_BLANK)))
14618 {
14619 /* Fast path */
14620 if (formatfloat(v, arg, NULL, writer) == -1)
14621 return -1;
14622 return 1;
14623 }
14624
14625 arg->sign = 1;
14626 if (formatfloat(v, arg, p_str, NULL) == -1)
14627 return -1;
14628 break;
14629
14630 case 'c':
14631 {
14632 Py_UCS4 ch = formatchar(v);
14633 if (ch == (Py_UCS4) -1)
14634 return -1;
14635 if (arg->width == -1 && arg->prec == -1) {
14636 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014637 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014638 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014639 return 1;
14640 }
14641 *p_str = PyUnicode_FromOrdinal(ch);
14642 break;
14643 }
14644
14645 default:
14646 PyErr_Format(PyExc_ValueError,
14647 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014648 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014649 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14650 (int)arg->ch,
14651 ctx->fmtpos - 1);
14652 return -1;
14653 }
14654 if (*p_str == NULL)
14655 return -1;
14656 assert (PyUnicode_Check(*p_str));
14657 return 0;
14658}
14659
14660static int
14661unicode_format_arg_output(struct unicode_formatter_t *ctx,
14662 struct unicode_format_arg_t *arg,
14663 PyObject *str)
14664{
14665 Py_ssize_t len;
14666 enum PyUnicode_Kind kind;
14667 void *pbuf;
14668 Py_ssize_t pindex;
14669 Py_UCS4 signchar;
14670 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014671 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014672 Py_ssize_t sublen;
14673 _PyUnicodeWriter *writer = &ctx->writer;
14674 Py_UCS4 fill;
14675
14676 fill = ' ';
14677 if (arg->sign && arg->flags & F_ZERO)
14678 fill = '0';
14679
14680 if (PyUnicode_READY(str) == -1)
14681 return -1;
14682
14683 len = PyUnicode_GET_LENGTH(str);
14684 if ((arg->width == -1 || arg->width <= len)
14685 && (arg->prec == -1 || arg->prec >= len)
14686 && !(arg->flags & (F_SIGN | F_BLANK)))
14687 {
14688 /* Fast path */
14689 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14690 return -1;
14691 return 0;
14692 }
14693
14694 /* Truncate the string for "s", "r" and "a" formats
14695 if the precision is set */
14696 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14697 if (arg->prec >= 0 && len > arg->prec)
14698 len = arg->prec;
14699 }
14700
14701 /* Adjust sign and width */
14702 kind = PyUnicode_KIND(str);
14703 pbuf = PyUnicode_DATA(str);
14704 pindex = 0;
14705 signchar = '\0';
14706 if (arg->sign) {
14707 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14708 if (ch == '-' || ch == '+') {
14709 signchar = ch;
14710 len--;
14711 pindex++;
14712 }
14713 else if (arg->flags & F_SIGN)
14714 signchar = '+';
14715 else if (arg->flags & F_BLANK)
14716 signchar = ' ';
14717 else
14718 arg->sign = 0;
14719 }
14720 if (arg->width < len)
14721 arg->width = len;
14722
14723 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014724 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014725 if (!(arg->flags & F_LJUST)) {
14726 if (arg->sign) {
14727 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014728 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014729 }
14730 else {
14731 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014732 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014733 }
14734 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014735 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14736 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014737 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014738 }
14739
Victor Stinnera47082312012-10-04 02:19:54 +020014740 buflen = arg->width;
14741 if (arg->sign && len == arg->width)
14742 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014743 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014744 return -1;
14745
14746 /* Write the sign if needed */
14747 if (arg->sign) {
14748 if (fill != ' ') {
14749 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14750 writer->pos += 1;
14751 }
14752 if (arg->width > len)
14753 arg->width--;
14754 }
14755
14756 /* Write the numeric prefix for "x", "X" and "o" formats
14757 if the alternate form is used.
14758 For example, write "0x" for the "%#x" format. */
14759 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14760 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14761 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14762 if (fill != ' ') {
14763 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14764 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14765 writer->pos += 2;
14766 pindex += 2;
14767 }
14768 arg->width -= 2;
14769 if (arg->width < 0)
14770 arg->width = 0;
14771 len -= 2;
14772 }
14773
14774 /* Pad left with the fill character if needed */
14775 if (arg->width > len && !(arg->flags & F_LJUST)) {
14776 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014777 unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014778 writer->pos += sublen;
14779 arg->width = len;
14780 }
14781
14782 /* If padding with spaces: write sign if needed and/or numeric prefix if
14783 the alternate form is used */
14784 if (fill == ' ') {
14785 if (arg->sign) {
14786 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14787 writer->pos += 1;
14788 }
14789 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14790 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14791 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14792 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14793 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14794 writer->pos += 2;
14795 pindex += 2;
14796 }
14797 }
14798
14799 /* Write characters */
14800 if (len) {
14801 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14802 str, pindex, len);
14803 writer->pos += len;
14804 }
14805
14806 /* Pad right with the fill character if needed */
14807 if (arg->width > len) {
14808 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014809 unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014810 writer->pos += sublen;
14811 }
14812 return 0;
14813}
14814
14815/* Helper of PyUnicode_Format(): format one arg.
14816 Return 0 on success, raise an exception and return -1 on error. */
14817static int
14818unicode_format_arg(struct unicode_formatter_t *ctx)
14819{
14820 struct unicode_format_arg_t arg;
14821 PyObject *str;
14822 int ret;
14823
Victor Stinner8dbd4212012-12-04 09:30:24 +010014824 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014825 if (arg.ch == '%') {
14826 ctx->fmtpos++;
14827 ctx->fmtcnt--;
14828 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14829 return -1;
14830 return 0;
14831 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014832 arg.flags = 0;
14833 arg.width = -1;
14834 arg.prec = -1;
14835 arg.sign = 0;
14836 str = NULL;
14837
Victor Stinnera47082312012-10-04 02:19:54 +020014838 ret = unicode_format_arg_parse(ctx, &arg);
14839 if (ret == -1)
14840 return -1;
14841
14842 ret = unicode_format_arg_format(ctx, &arg, &str);
14843 if (ret == -1)
14844 return -1;
14845
14846 if (ret != 1) {
14847 ret = unicode_format_arg_output(ctx, &arg, str);
14848 Py_DECREF(str);
14849 if (ret == -1)
14850 return -1;
14851 }
14852
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014853 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014854 PyErr_SetString(PyExc_TypeError,
14855 "not all arguments converted during string formatting");
14856 return -1;
14857 }
14858 return 0;
14859}
14860
Alexander Belopolsky40018472011-02-26 01:02:56 +000014861PyObject *
14862PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014863{
Victor Stinnera47082312012-10-04 02:19:54 +020014864 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014865
Guido van Rossumd57fd912000-03-10 22:53:23 +000014866 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014867 PyErr_BadInternalCall();
14868 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014869 }
Victor Stinnera47082312012-10-04 02:19:54 +020014870
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014871 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014872 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014873
14874 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014875 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14876 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14877 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14878 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014879
Victor Stinner8f674cc2013-04-17 23:02:17 +020014880 _PyUnicodeWriter_Init(&ctx.writer);
14881 ctx.writer.min_length = ctx.fmtcnt + 100;
14882 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014883
Guido van Rossumd57fd912000-03-10 22:53:23 +000014884 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014885 ctx.arglen = PyTuple_Size(args);
14886 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014887 }
14888 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014889 ctx.arglen = -1;
14890 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014891 }
Victor Stinnera47082312012-10-04 02:19:54 +020014892 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014893 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014894 ctx.dict = args;
14895 else
14896 ctx.dict = NULL;
14897 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014898
Victor Stinnera47082312012-10-04 02:19:54 +020014899 while (--ctx.fmtcnt >= 0) {
14900 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014901 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014902
14903 nonfmtpos = ctx.fmtpos++;
14904 while (ctx.fmtcnt >= 0 &&
14905 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14906 ctx.fmtpos++;
14907 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014908 }
Victor Stinnera47082312012-10-04 02:19:54 +020014909 if (ctx.fmtcnt < 0) {
14910 ctx.fmtpos--;
14911 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014912 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014913
Victor Stinnercfc4c132013-04-03 01:48:39 +020014914 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
14915 nonfmtpos, ctx.fmtpos) < 0)
14916 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014917 }
14918 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014919 ctx.fmtpos++;
14920 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000014921 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020014922 }
14923 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020014924
Victor Stinnera47082312012-10-04 02:19:54 +020014925 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014926 PyErr_SetString(PyExc_TypeError,
14927 "not all arguments converted during string formatting");
14928 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014929 }
14930
Victor Stinnera47082312012-10-04 02:19:54 +020014931 if (ctx.args_owned) {
14932 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014933 }
Victor Stinnera47082312012-10-04 02:19:54 +020014934 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014935
Benjamin Peterson29060642009-01-31 22:14:21 +000014936 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020014937 _PyUnicodeWriter_Dealloc(&ctx.writer);
14938 if (ctx.args_owned) {
14939 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014940 }
14941 return NULL;
14942}
14943
Jeremy Hylton938ace62002-07-17 16:30:39 +000014944static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000014945unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
14946
Tim Peters6d6c1a32001-08-02 04:15:00 +000014947static PyObject *
14948unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14949{
Benjamin Peterson29060642009-01-31 22:14:21 +000014950 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014951 static char *kwlist[] = {"object", "encoding", "errors", 0};
14952 char *encoding = NULL;
14953 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000014954
Benjamin Peterson14339b62009-01-31 16:36:08 +000014955 if (type != &PyUnicode_Type)
14956 return unicode_subtype_new(type, args, kwds);
14957 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000014958 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000014959 return NULL;
14960 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020014961 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000014962 if (encoding == NULL && errors == NULL)
14963 return PyObject_Str(x);
14964 else
Benjamin Peterson29060642009-01-31 22:14:21 +000014965 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000014966}
14967
Guido van Rossume023fe02001-08-30 03:12:59 +000014968static PyObject *
14969unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
14970{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014971 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014972 Py_ssize_t length, char_size;
14973 int share_wstr, share_utf8;
14974 unsigned int kind;
14975 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000014976
Benjamin Peterson14339b62009-01-31 16:36:08 +000014977 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014978
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014979 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014980 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000014981 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014982 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050014983 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060014984 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014985 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060014986 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014987
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014988 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014989 if (self == NULL) {
14990 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014991 return NULL;
14992 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020014993 kind = PyUnicode_KIND(unicode);
14994 length = PyUnicode_GET_LENGTH(unicode);
14995
14996 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020014997#ifdef Py_DEBUG
14998 _PyUnicode_HASH(self) = -1;
14999#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015000 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015001#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015002 _PyUnicode_STATE(self).interned = 0;
15003 _PyUnicode_STATE(self).kind = kind;
15004 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015005 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015006 _PyUnicode_STATE(self).ready = 1;
15007 _PyUnicode_WSTR(self) = NULL;
15008 _PyUnicode_UTF8_LENGTH(self) = 0;
15009 _PyUnicode_UTF8(self) = NULL;
15010 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015011 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015012
15013 share_utf8 = 0;
15014 share_wstr = 0;
15015 if (kind == PyUnicode_1BYTE_KIND) {
15016 char_size = 1;
15017 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15018 share_utf8 = 1;
15019 }
15020 else if (kind == PyUnicode_2BYTE_KIND) {
15021 char_size = 2;
15022 if (sizeof(wchar_t) == 2)
15023 share_wstr = 1;
15024 }
15025 else {
15026 assert(kind == PyUnicode_4BYTE_KIND);
15027 char_size = 4;
15028 if (sizeof(wchar_t) == 4)
15029 share_wstr = 1;
15030 }
15031
15032 /* Ensure we won't overflow the length. */
15033 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15034 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015035 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015037 data = PyObject_MALLOC((length + 1) * char_size);
15038 if (data == NULL) {
15039 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015040 goto onError;
15041 }
15042
Victor Stinnerc3c74152011-10-02 20:39:55 +020015043 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015044 if (share_utf8) {
15045 _PyUnicode_UTF8_LENGTH(self) = length;
15046 _PyUnicode_UTF8(self) = data;
15047 }
15048 if (share_wstr) {
15049 _PyUnicode_WSTR_LENGTH(self) = length;
15050 _PyUnicode_WSTR(self) = (wchar_t *)data;
15051 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015052
Christian Heimesf051e432016-09-13 20:22:02 +020015053 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015054 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015055 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015056#ifdef Py_DEBUG
15057 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15058#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015059 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015060 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015061
15062onError:
15063 Py_DECREF(unicode);
15064 Py_DECREF(self);
15065 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015066}
15067
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015068PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015069"str(object='') -> str\n\
15070str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015071\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015072Create a new string object from the given object. If encoding or\n\
15073errors is specified, then the object must expose a data buffer\n\
15074that will be decoded using the given encoding and error handler.\n\
15075Otherwise, returns the result of object.__str__() (if defined)\n\
15076or repr(object).\n\
15077encoding defaults to sys.getdefaultencoding().\n\
15078errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015079
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015080static PyObject *unicode_iter(PyObject *seq);
15081
Guido van Rossumd57fd912000-03-10 22:53:23 +000015082PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015083 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015084 "str", /* tp_name */
15085 sizeof(PyUnicodeObject), /* tp_basicsize */
15086 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015087 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015088 (destructor)unicode_dealloc, /* tp_dealloc */
15089 0, /* tp_print */
15090 0, /* tp_getattr */
15091 0, /* tp_setattr */
15092 0, /* tp_reserved */
15093 unicode_repr, /* tp_repr */
15094 &unicode_as_number, /* tp_as_number */
15095 &unicode_as_sequence, /* tp_as_sequence */
15096 &unicode_as_mapping, /* tp_as_mapping */
15097 (hashfunc) unicode_hash, /* tp_hash*/
15098 0, /* tp_call*/
15099 (reprfunc) unicode_str, /* tp_str */
15100 PyObject_GenericGetAttr, /* tp_getattro */
15101 0, /* tp_setattro */
15102 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015103 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015104 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15105 unicode_doc, /* tp_doc */
15106 0, /* tp_traverse */
15107 0, /* tp_clear */
15108 PyUnicode_RichCompare, /* tp_richcompare */
15109 0, /* tp_weaklistoffset */
15110 unicode_iter, /* tp_iter */
15111 0, /* tp_iternext */
15112 unicode_methods, /* tp_methods */
15113 0, /* tp_members */
15114 0, /* tp_getset */
15115 &PyBaseObject_Type, /* tp_base */
15116 0, /* tp_dict */
15117 0, /* tp_descr_get */
15118 0, /* tp_descr_set */
15119 0, /* tp_dictoffset */
15120 0, /* tp_init */
15121 0, /* tp_alloc */
15122 unicode_new, /* tp_new */
15123 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015124};
15125
15126/* Initialize the Unicode implementation */
15127
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015128_PyInitError
15129_PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015130{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015131 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015132 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015133 0x000A, /* LINE FEED */
15134 0x000D, /* CARRIAGE RETURN */
15135 0x001C, /* FILE SEPARATOR */
15136 0x001D, /* GROUP SEPARATOR */
15137 0x001E, /* RECORD SEPARATOR */
15138 0x0085, /* NEXT LINE */
15139 0x2028, /* LINE SEPARATOR */
15140 0x2029, /* PARAGRAPH SEPARATOR */
15141 };
15142
Fred Drakee4315f52000-05-09 19:53:39 +000015143 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015144 _Py_INCREF_UNICODE_EMPTY();
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015145 if (!unicode_empty) {
15146 return _Py_INIT_ERR("Can't create empty string");
15147 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020015148 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015149
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015150 if (PyType_Ready(&PyUnicode_Type) < 0) {
15151 return _Py_INIT_ERR("Can't initialize unicode type");
15152 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000015153
15154 /* initialize the linebreak bloom filter */
15155 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015156 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015157 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015158
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015159 if (PyType_Ready(&EncodingMapType) < 0) {
15160 return _Py_INIT_ERR("Can't initialize encoding map type");
15161 }
15162 if (PyType_Ready(&PyFieldNameIter_Type) < 0) {
15163 return _Py_INIT_ERR("Can't initialize field name iterator type");
15164 }
15165 if (PyType_Ready(&PyFormatterIter_Type) < 0) {
15166 return _Py_INIT_ERR("Can't initialize formatter iter type");
15167 }
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +010015168 return _Py_INIT_OK();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015169}
15170
15171/* Finalize the Unicode implementation */
15172
Christian Heimesa156e092008-02-16 07:38:31 +000015173int
15174PyUnicode_ClearFreeList(void)
15175{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015176 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015177}
15178
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015179
Walter Dörwald16807132007-05-25 13:52:07 +000015180void
15181PyUnicode_InternInPlace(PyObject **p)
15182{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015183 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015184 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015185#ifdef Py_DEBUG
15186 assert(s != NULL);
15187 assert(_PyUnicode_CHECK(s));
15188#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015189 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015190 return;
15191#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015192 /* If it's a subclass, we don't really know what putting
15193 it in the interned dict might do. */
15194 if (!PyUnicode_CheckExact(s))
15195 return;
15196 if (PyUnicode_CHECK_INTERNED(s))
15197 return;
15198 if (interned == NULL) {
15199 interned = PyDict_New();
15200 if (interned == NULL) {
15201 PyErr_Clear(); /* Don't leave an exception */
15202 return;
15203 }
15204 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015205 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015206 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015207 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015208 if (t == NULL) {
15209 PyErr_Clear();
15210 return;
15211 }
15212 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015213 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015214 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015215 return;
15216 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015217 /* The two references in interned are not counted by refcnt.
15218 The deallocator will take care of this */
15219 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015220 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015221}
15222
15223void
15224PyUnicode_InternImmortal(PyObject **p)
15225{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015226 PyUnicode_InternInPlace(p);
15227 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015228 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015229 Py_INCREF(*p);
15230 }
Walter Dörwald16807132007-05-25 13:52:07 +000015231}
15232
15233PyObject *
15234PyUnicode_InternFromString(const char *cp)
15235{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015236 PyObject *s = PyUnicode_FromString(cp);
15237 if (s == NULL)
15238 return NULL;
15239 PyUnicode_InternInPlace(&s);
15240 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015241}
15242
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015243
15244#if defined(WITH_VALGRIND) || defined(__INSURE__)
15245static void
15246unicode_release_interned(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015247{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015248 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015249 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015250 Py_ssize_t i, n;
15251 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015252
Benjamin Peterson14339b62009-01-31 16:36:08 +000015253 if (interned == NULL || !PyDict_Check(interned))
15254 return;
15255 keys = PyDict_Keys(interned);
15256 if (keys == NULL || !PyList_Check(keys)) {
15257 PyErr_Clear();
15258 return;
15259 }
Walter Dörwald16807132007-05-25 13:52:07 +000015260
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015261 /* Since unicode_release_interned() is intended to help a leak
Benjamin Peterson14339b62009-01-31 16:36:08 +000015262 detector, interned unicode strings are not forcibly deallocated;
15263 rather, we give them their stolen references back, and then clear
15264 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015265
Benjamin Peterson14339b62009-01-31 16:36:08 +000015266 n = PyList_GET_SIZE(keys);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015267#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015268 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015269 n);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015270#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015271 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015272 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015273 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015274 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015276 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015277 case SSTATE_NOT_INTERNED:
15278 /* XXX Shouldn't happen */
15279 break;
15280 case SSTATE_INTERNED_IMMORTAL:
15281 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015282 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015283 break;
15284 case SSTATE_INTERNED_MORTAL:
15285 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015286 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015287 break;
15288 default:
15289 Py_FatalError("Inconsistent interned string state.");
15290 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015291 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015292 }
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015293#ifdef INTERNED_STATS
Benjamin Peterson14339b62009-01-31 16:36:08 +000015294 fprintf(stderr, "total size of all interned strings: "
15295 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15296 "mortal/immortal\n", mortal_size, immortal_size);
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015297#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015298 Py_DECREF(keys);
15299 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015300 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015301}
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015302#endif
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015303
15304
15305/********************* Unicode Iterator **************************/
15306
15307typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015308 PyObject_HEAD
15309 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015310 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015311} unicodeiterobject;
15312
15313static void
15314unicodeiter_dealloc(unicodeiterobject *it)
15315{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015316 _PyObject_GC_UNTRACK(it);
15317 Py_XDECREF(it->it_seq);
15318 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015319}
15320
15321static int
15322unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15323{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015324 Py_VISIT(it->it_seq);
15325 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015326}
15327
15328static PyObject *
15329unicodeiter_next(unicodeiterobject *it)
15330{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015331 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015332
Benjamin Peterson14339b62009-01-31 16:36:08 +000015333 assert(it != NULL);
15334 seq = it->it_seq;
15335 if (seq == NULL)
15336 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015337 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015338
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015339 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15340 int kind = PyUnicode_KIND(seq);
15341 void *data = PyUnicode_DATA(seq);
15342 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15343 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015344 if (item != NULL)
15345 ++it->it_index;
15346 return item;
15347 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015348
Benjamin Peterson14339b62009-01-31 16:36:08 +000015349 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015350 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015351 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015352}
15353
15354static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015355unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015356{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015357 Py_ssize_t len = 0;
15358 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015359 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015360 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015361}
15362
15363PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15364
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015365static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015366unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015367{
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015368 _Py_IDENTIFIER(iter);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015369 if (it->it_seq != NULL) {
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015370 return Py_BuildValue("N(O)n", _PyEval_GetBuiltinId(&PyId_iter),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015371 it->it_seq, it->it_index);
15372 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015373 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015374 if (u == NULL)
15375 return NULL;
Serhiy Storchakabb86bf42018-12-11 08:28:18 +020015376 return Py_BuildValue("N(N)", _PyEval_GetBuiltinId(&PyId_iter), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015377 }
15378}
15379
15380PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15381
15382static PyObject *
15383unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15384{
15385 Py_ssize_t index = PyLong_AsSsize_t(state);
15386 if (index == -1 && PyErr_Occurred())
15387 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015388 if (it->it_seq != NULL) {
15389 if (index < 0)
15390 index = 0;
15391 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15392 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15393 it->it_index = index;
15394 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015395 Py_RETURN_NONE;
15396}
15397
15398PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15399
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015400static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015401 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015402 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015403 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15404 reduce_doc},
15405 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15406 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015407 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015408};
15409
15410PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015411 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15412 "str_iterator", /* tp_name */
15413 sizeof(unicodeiterobject), /* tp_basicsize */
15414 0, /* tp_itemsize */
15415 /* methods */
15416 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15417 0, /* tp_print */
15418 0, /* tp_getattr */
15419 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015420 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015421 0, /* tp_repr */
15422 0, /* tp_as_number */
15423 0, /* tp_as_sequence */
15424 0, /* tp_as_mapping */
15425 0, /* tp_hash */
15426 0, /* tp_call */
15427 0, /* tp_str */
15428 PyObject_GenericGetAttr, /* tp_getattro */
15429 0, /* tp_setattro */
15430 0, /* tp_as_buffer */
15431 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15432 0, /* tp_doc */
15433 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15434 0, /* tp_clear */
15435 0, /* tp_richcompare */
15436 0, /* tp_weaklistoffset */
15437 PyObject_SelfIter, /* tp_iter */
15438 (iternextfunc)unicodeiter_next, /* tp_iternext */
15439 unicodeiter_methods, /* tp_methods */
15440 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015441};
15442
15443static PyObject *
15444unicode_iter(PyObject *seq)
15445{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015446 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015447
Benjamin Peterson14339b62009-01-31 16:36:08 +000015448 if (!PyUnicode_Check(seq)) {
15449 PyErr_BadInternalCall();
15450 return NULL;
15451 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015452 if (PyUnicode_READY(seq) == -1)
15453 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015454 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15455 if (it == NULL)
15456 return NULL;
15457 it->it_index = 0;
15458 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015459 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015460 _PyObject_GC_TRACK(it);
15461 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015462}
15463
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015464
15465size_t
15466Py_UNICODE_strlen(const Py_UNICODE *u)
15467{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015468 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015469}
15470
15471Py_UNICODE*
15472Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15473{
15474 Py_UNICODE *u = s1;
15475 while ((*u++ = *s2++));
15476 return s1;
15477}
15478
15479Py_UNICODE*
15480Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15481{
15482 Py_UNICODE *u = s1;
15483 while ((*u++ = *s2++))
15484 if (n-- == 0)
15485 break;
15486 return s1;
15487}
15488
15489Py_UNICODE*
15490Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15491{
15492 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015493 u1 += wcslen(u1);
15494 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015495 return s1;
15496}
15497
15498int
15499Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15500{
15501 while (*s1 && *s2 && *s1 == *s2)
15502 s1++, s2++;
15503 if (*s1 && *s2)
15504 return (*s1 < *s2) ? -1 : +1;
15505 if (*s1)
15506 return 1;
15507 if (*s2)
15508 return -1;
15509 return 0;
15510}
15511
15512int
15513Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15514{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015515 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015516 for (; n != 0; n--) {
15517 u1 = *s1;
15518 u2 = *s2;
15519 if (u1 != u2)
15520 return (u1 < u2) ? -1 : +1;
15521 if (u1 == '\0')
15522 return 0;
15523 s1++;
15524 s2++;
15525 }
15526 return 0;
15527}
15528
15529Py_UNICODE*
15530Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15531{
15532 const Py_UNICODE *p;
15533 for (p = s; *p; p++)
15534 if (*p == c)
15535 return (Py_UNICODE*)p;
15536 return NULL;
15537}
15538
15539Py_UNICODE*
15540Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15541{
15542 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015543 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015544 while (p != s) {
15545 p--;
15546 if (*p == c)
15547 return (Py_UNICODE*)p;
15548 }
15549 return NULL;
15550}
Victor Stinner331ea922010-08-10 16:37:20 +000015551
Victor Stinner71133ff2010-09-01 23:43:53 +000015552Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015553PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015554{
Victor Stinner577db2c2011-10-11 22:12:48 +020015555 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015556 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015557
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015558 if (!PyUnicode_Check(unicode)) {
15559 PyErr_BadArgument();
15560 return NULL;
15561 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015562 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015563 if (u == NULL)
15564 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015565 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015566 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015567 PyErr_NoMemory();
15568 return NULL;
15569 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015570 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015571 size *= sizeof(Py_UNICODE);
15572 copy = PyMem_Malloc(size);
15573 if (copy == NULL) {
15574 PyErr_NoMemory();
15575 return NULL;
15576 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015577 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015578 return copy;
15579}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015580
Victor Stinnerfecc4f22019-03-19 14:20:29 +010015581
15582void
15583_PyUnicode_Fini(void)
15584{
15585#if defined(WITH_VALGRIND) || defined(__INSURE__)
15586 /* Insure++ is a memory analysis tool that aids in discovering
15587 * memory leaks and other memory problems. On Python exit, the
15588 * interned string dictionaries are flagged as being in use at exit
15589 * (which it is). Under normal circumstances, this is fine because
15590 * the memory will be automatically reclaimed by the system. Under
15591 * memory debugging, it's a huge source of useless noise, so we
15592 * trade off slower shutdown for less distraction in the memory
15593 * reports. -baw
15594 */
15595 unicode_release_interned();
15596#endif /* __INSURE__ */
15597
15598 Py_CLEAR(unicode_empty);
15599
15600 for (Py_ssize_t i = 0; i < 256; i++) {
15601 Py_CLEAR(unicode_latin1[i]);
15602 }
15603 _PyUnicode_ClearStaticStrings();
15604 (void)PyUnicode_ClearFreeList();
15605}
15606
15607
Georg Brandl66c221e2010-10-14 07:04:07 +000015608/* A _string module, to export formatter_parser and formatter_field_name_split
15609 to the string.Formatter class implemented in Python. */
15610
15611static PyMethodDef _string_methods[] = {
15612 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15613 METH_O, PyDoc_STR("split the argument as a field name")},
15614 {"formatter_parser", (PyCFunction) formatter_parser,
15615 METH_O, PyDoc_STR("parse the argument as a format string")},
15616 {NULL, NULL}
15617};
15618
15619static struct PyModuleDef _string_module = {
15620 PyModuleDef_HEAD_INIT,
15621 "_string",
15622 PyDoc_STR("string helper module"),
15623 0,
15624 _string_methods,
15625 NULL,
15626 NULL,
15627 NULL,
15628 NULL
15629};
15630
15631PyMODINIT_FUNC
15632PyInit__string(void)
15633{
15634 return PyModule_Create(&_string_module);
15635}
15636
15637
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015638#ifdef __cplusplus
15639}
15640#endif