blob: 3da40ddc58986beb060e0ae86b0d7e4675c342f2 [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
Larry Hastings61272b72014-01-07 12:41:53 -080054/*[clinic input]
INADA Naoki15f94592017-01-16 21:49:13 +090055class str "PyObject *" "&PyUnicode_Type"
Larry Hastings61272b72014-01-07 12:41:53 -080056[clinic start generated code]*/
INADA Naoki3ae20562017-01-16 20:41:20 +090057/*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
58
59/*[python input]
60class Py_UCS4_converter(CConverter):
61 type = 'Py_UCS4'
62 converter = 'convert_uc'
63
64 def converter_init(self):
65 if self.default is not unspecified:
66 self.c_default = ascii(self.default)
67 if len(self.c_default) > 4 or self.c_default[0] != "'":
68 self.c_default = hex(ord(self.default))
69
70[python start generated code]*/
71/*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
Larry Hastings44e2eaa2013-11-23 15:37:55 -080072
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000073/* --- Globals ------------------------------------------------------------
74
Serhiy Storchaka05997252013-01-26 12:14:02 +020075NOTE: In the interpreter's initialization phase, some globals are currently
76 initialized dynamically as needed. In the process Unicode objects may
77 be created before the Unicode type is ready.
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000078
79*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000080
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000081
82#ifdef __cplusplus
83extern "C" {
84#endif
85
Victor Stinner8faf8212011-12-08 22:14:11 +010086/* Maximum code point of Unicode 6.0: 0x10ffff (1,114,111) */
87#define MAX_UNICODE 0x10ffff
88
Victor Stinner910337b2011-10-03 03:20:16 +020089#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020090# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020091#else
92# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
93#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020094
Victor Stinnere90fe6a2011-10-01 16:48:13 +020095#define _PyUnicode_UTF8(op) \
96 (((PyCompactUnicodeObject*)(op))->utf8)
97#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020098 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020099 assert(PyUnicode_IS_READY(op)), \
100 PyUnicode_IS_COMPACT_ASCII(op) ? \
101 ((char*)((PyASCIIObject*)(op) + 1)) : \
102 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +0200103#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200104 (((PyCompactUnicodeObject*)(op))->utf8_length)
105#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200106 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200107 assert(PyUnicode_IS_READY(op)), \
108 PyUnicode_IS_COMPACT_ASCII(op) ? \
109 ((PyASCIIObject*)(op))->length : \
110 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_WSTR(op) \
112 (((PyASCIIObject*)(op))->wstr)
113#define _PyUnicode_WSTR_LENGTH(op) \
114 (((PyCompactUnicodeObject*)(op))->wstr_length)
115#define _PyUnicode_LENGTH(op) \
116 (((PyASCIIObject *)(op))->length)
117#define _PyUnicode_STATE(op) \
118 (((PyASCIIObject *)(op))->state)
119#define _PyUnicode_HASH(op) \
120 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200121#define _PyUnicode_KIND(op) \
122 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200123 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200124#define _PyUnicode_GET_LENGTH(op) \
125 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200126 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200127#define _PyUnicode_DATA_ANY(op) \
128 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200129
Victor Stinner910337b2011-10-03 03:20:16 +0200130#undef PyUnicode_READY
131#define PyUnicode_READY(op) \
132 (assert(_PyUnicode_CHECK(op)), \
133 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200134 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100135 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200136
Victor Stinnerc379ead2011-10-03 12:52:27 +0200137#define _PyUnicode_SHARE_UTF8(op) \
138 (assert(_PyUnicode_CHECK(op)), \
139 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
140 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
141#define _PyUnicode_SHARE_WSTR(op) \
142 (assert(_PyUnicode_CHECK(op)), \
143 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
144
Victor Stinner829c0ad2011-10-03 01:08:02 +0200145/* true if the Unicode object has an allocated UTF-8 memory block
146 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200147#define _PyUnicode_HAS_UTF8_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200148 ((!PyUnicode_IS_COMPACT_ASCII(op) \
Victor Stinner910337b2011-10-03 03:20:16 +0200149 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200150 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
151
Victor Stinner03490912011-10-03 23:45:12 +0200152/* true if the Unicode object has an allocated wstr memory block
153 (not shared with other data) */
154#define _PyUnicode_HAS_WSTR_MEMORY(op) \
Victor Stinnere699e5a2013-07-15 18:22:47 +0200155 ((_PyUnicode_WSTR(op) && \
Victor Stinner03490912011-10-03 23:45:12 +0200156 (!PyUnicode_IS_READY(op) || \
157 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
158
Victor Stinner910337b2011-10-03 03:20:16 +0200159/* Generic helper macro to convert characters of different types.
160 from_type and to_type have to be valid type names, begin and end
161 are pointers to the source characters which should be of type
162 "from_type *". to is a pointer of type "to_type *" and points to the
163 buffer where the result characters are written to. */
164#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
165 do { \
Victor Stinner4a587072013-11-19 12:54:53 +0100166 to_type *_to = (to_type *)(to); \
167 const from_type *_iter = (from_type *)(begin); \
168 const from_type *_end = (from_type *)(end); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200169 Py_ssize_t n = (_end) - (_iter); \
170 const from_type *_unrolled_end = \
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +0200171 _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
Antoine Pitroue459a082011-10-11 20:58:41 +0200172 while (_iter < (_unrolled_end)) { \
173 _to[0] = (to_type) _iter[0]; \
174 _to[1] = (to_type) _iter[1]; \
175 _to[2] = (to_type) _iter[2]; \
176 _to[3] = (to_type) _iter[3]; \
177 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200178 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200179 while (_iter < (_end)) \
180 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200181 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200182
Victor Stinnerfdfbf782015-10-09 00:33:49 +0200183#ifdef MS_WINDOWS
184 /* On Windows, overallocate by 50% is the best factor */
185# define OVERALLOCATE_FACTOR 2
186#else
187 /* On Linux, overallocate by 25% is the best factor */
188# define OVERALLOCATE_FACTOR 4
189#endif
190
Walter Dörwald16807132007-05-25 13:52:07 +0000191/* This dictionary holds all interned unicode strings. Note that references
192 to strings in this dictionary are *not* counted in the string's ob_refcnt.
193 When the interned string reaches a refcnt of 0 the string deallocation
194 function will delete the reference from this dictionary.
195
196 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000197 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000198*/
Serhiy Storchaka05997252013-01-26 12:14:02 +0200199static PyObject *interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +0000200
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000201/* The empty Unicode object is shared to improve performance. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200202static PyObject *unicode_empty = NULL;
Serhiy Storchaka05997252013-01-26 12:14:02 +0200203
Serhiy Storchaka678db842013-01-26 12:16:36 +0200204#define _Py_INCREF_UNICODE_EMPTY() \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200205 do { \
206 if (unicode_empty != NULL) \
207 Py_INCREF(unicode_empty); \
208 else { \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200209 unicode_empty = PyUnicode_New(0, 0); \
210 if (unicode_empty != NULL) { \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200211 Py_INCREF(unicode_empty); \
Serhiy Storchaka678db842013-01-26 12:16:36 +0200212 assert(_PyUnicode_CheckConsistency(unicode_empty, 1)); \
213 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200214 } \
Serhiy Storchaka05997252013-01-26 12:14:02 +0200215 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000216
Serhiy Storchaka678db842013-01-26 12:16:36 +0200217#define _Py_RETURN_UNICODE_EMPTY() \
218 do { \
219 _Py_INCREF_UNICODE_EMPTY(); \
220 return unicode_empty; \
221 } while (0)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000222
Victor Stinner59423e32018-11-26 13:40:01 +0100223static inline void
224unicode_fill(enum PyUnicode_Kind kind, void *data, Py_UCS4 value,
225 Py_ssize_t start, Py_ssize_t length)
226{
227 assert(0 <= start);
228 assert(kind != PyUnicode_WCHAR_KIND);
229 switch (kind) {
230 case PyUnicode_1BYTE_KIND: {
231 Py_UCS1 ch = (unsigned char)value;
232 Py_UCS1 *to = (Py_UCS1 *)data + start;
233 memset(to, ch, length);
234 break;
235 }
236 case PyUnicode_2BYTE_KIND: {
237 Py_UCS2 ch = (Py_UCS2)value;
238 Py_UCS2 *to = (Py_UCS2 *)data + start;
239 const Py_UCS2 *end = to + length;
240 for (; to < end; ++to) *to = ch;
241 break;
242 }
243 case PyUnicode_4BYTE_KIND: {
244 Py_UCS4 ch = value;
245 Py_UCS4 * to = (Py_UCS4 *)data + start;
246 const Py_UCS4 *end = to + length;
247 for (; to < end; ++to) *to = ch;
248 break;
249 }
250 default: Py_UNREACHABLE();
251 }
252}
253
254
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200255/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700256static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200257_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
258
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200259/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200260static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200261
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000262/* Single character Unicode strings in the Latin-1 range are being
263 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200264static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000265
Christian Heimes190d79e2008-01-30 11:58:22 +0000266/* Fast detection of the most frequent whitespace characters */
267const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000268 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000269/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000271/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000272/* case 0x000C: * FORM FEED */
273/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000274 0, 1, 1, 1, 1, 1, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000276/* case 0x001C: * FILE SEPARATOR */
277/* case 0x001D: * GROUP SEPARATOR */
278/* case 0x001E: * RECORD SEPARATOR */
279/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000280 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000281/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000282 1, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000286
Benjamin Peterson14339b62009-01-31 16:36:08 +0000287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 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,
294 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000295};
296
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200297/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200298static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200299static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100300static int unicode_modifiable(PyObject *unicode);
301
Victor Stinnerfe226c02011-10-03 03:52:20 +0200302
Alexander Belopolsky40018472011-02-26 01:02:56 +0000303static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100304_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200305static PyObject *
306_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
307static PyObject *
308_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
309
310static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000311unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000312 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100313 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000314 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
315
Alexander Belopolsky40018472011-02-26 01:02:56 +0000316static void
317raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300318 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100319 PyObject *unicode,
320 Py_ssize_t startpos, Py_ssize_t endpos,
321 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000322
Christian Heimes190d79e2008-01-30 11:58:22 +0000323/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200324static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000325 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000326/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000327/* 0x000B, * LINE TABULATION */
328/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000329/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000330 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000331 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000332/* 0x001C, * FILE SEPARATOR */
333/* 0x001D, * GROUP SEPARATOR */
334/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000335 0, 0, 0, 0, 1, 1, 1, 0,
336 0, 0, 0, 0, 0, 0, 0, 0,
337 0, 0, 0, 0, 0, 0, 0, 0,
338 0, 0, 0, 0, 0, 0, 0, 0,
339 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000340
Benjamin Peterson14339b62009-01-31 16:36:08 +0000341 0, 0, 0, 0, 0, 0, 0, 0,
342 0, 0, 0, 0, 0, 0, 0, 0,
343 0, 0, 0, 0, 0, 0, 0, 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,
348 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000349};
350
INADA Naoki3ae20562017-01-16 20:41:20 +0900351static int convert_uc(PyObject *obj, void *addr);
352
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300353#include "clinic/unicodeobject.c.h"
354
Victor Stinner3d4226a2018-08-29 22:21:32 +0200355_Py_error_handler
356_Py_GetErrorHandler(const char *errors)
Victor Stinner50149202015-09-22 00:26:54 +0200357{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200358 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200359 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200360 }
361 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200362 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200363 }
364 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200365 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200366 }
367 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200368 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200369 }
370 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200371 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200372 }
373 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200374 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200375 }
376 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200377 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200378 }
Victor Stinner50149202015-09-22 00:26:54 +0200379 return _Py_ERROR_OTHER;
380}
381
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300382/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
383 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000384Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000385PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000386{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000387#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000388 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000389#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000390 /* This is actually an illegal character, so it should
391 not be passed to unichr. */
392 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000393#endif
394}
395
Victor Stinner910337b2011-10-03 03:20:16 +0200396#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200397int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100398_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200399{
Victor Stinner50fe3f82018-10-26 18:47:15 +0200400#define ASSERT(expr) _PyObject_ASSERT(op, (expr))
401
Victor Stinner910337b2011-10-03 03:20:16 +0200402 PyASCIIObject *ascii;
403 unsigned int kind;
404
Victor Stinner50fe3f82018-10-26 18:47:15 +0200405 ASSERT(PyUnicode_Check(op));
Victor Stinner910337b2011-10-03 03:20:16 +0200406
407 ascii = (PyASCIIObject *)op;
408 kind = ascii->state.kind;
409
Victor Stinnera3b334d2011-10-03 13:53:37 +0200410 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200411 ASSERT(kind == PyUnicode_1BYTE_KIND);
412 ASSERT(ascii->state.ready == 1);
Victor Stinner910337b2011-10-03 03:20:16 +0200413 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200414 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200415 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200416 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200417
Victor Stinnera41463c2011-10-04 01:05:08 +0200418 if (ascii->state.compact == 1) {
419 data = compact + 1;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200420 ASSERT(kind == PyUnicode_1BYTE_KIND
Victor Stinner910337b2011-10-03 03:20:16 +0200421 || kind == PyUnicode_2BYTE_KIND
422 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200423 ASSERT(ascii->state.ascii == 0);
424 ASSERT(ascii->state.ready == 1);
425 ASSERT (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100426 }
427 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200428 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
429
430 data = unicode->data.any;
431 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200432 ASSERT(ascii->length == 0);
433 ASSERT(ascii->hash == -1);
434 ASSERT(ascii->state.compact == 0);
435 ASSERT(ascii->state.ascii == 0);
436 ASSERT(ascii->state.ready == 0);
437 ASSERT(ascii->state.interned == SSTATE_NOT_INTERNED);
438 ASSERT(ascii->wstr != NULL);
439 ASSERT(data == NULL);
440 ASSERT(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200441 }
442 else {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200443 ASSERT(kind == PyUnicode_1BYTE_KIND
Victor Stinnera41463c2011-10-04 01:05:08 +0200444 || kind == PyUnicode_2BYTE_KIND
445 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200446 ASSERT(ascii->state.compact == 0);
447 ASSERT(ascii->state.ready == 1);
448 ASSERT(data != NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200449 if (ascii->state.ascii) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200450 ASSERT (compact->utf8 == data);
451 ASSERT (compact->utf8_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200452 }
453 else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200454 ASSERT (compact->utf8 != data);
Victor Stinnera41463c2011-10-04 01:05:08 +0200455 }
456 }
457 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200458 if (
459#if SIZEOF_WCHAR_T == 2
460 kind == PyUnicode_2BYTE_KIND
461#else
462 kind == PyUnicode_4BYTE_KIND
463#endif
464 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200465 {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200466 ASSERT(ascii->wstr == data);
467 ASSERT(compact->wstr_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200468 } else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200469 ASSERT(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200470 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200471
472 if (compact->utf8 == NULL)
Victor Stinner50fe3f82018-10-26 18:47:15 +0200473 ASSERT(compact->utf8_length == 0);
Victor Stinnera41463c2011-10-04 01:05:08 +0200474 if (ascii->wstr == NULL)
Victor Stinner50fe3f82018-10-26 18:47:15 +0200475 ASSERT(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200476 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200477 /* check that the best kind is used */
478 if (check_content && kind != PyUnicode_WCHAR_KIND)
479 {
480 Py_ssize_t i;
481 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200482 void *data;
483 Py_UCS4 ch;
484
485 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200486 for (i=0; i < ascii->length; i++)
487 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200488 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200489 if (ch > maxchar)
490 maxchar = ch;
491 }
492 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100493 if (ascii->state.ascii == 0) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200494 ASSERT(maxchar >= 128);
495 ASSERT(maxchar <= 255);
Victor Stinner77faf692011-11-20 18:56:05 +0100496 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200497 else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200498 ASSERT(maxchar < 128);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200499 }
Victor Stinner77faf692011-11-20 18:56:05 +0100500 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200501 ASSERT(maxchar >= 0x100);
502 ASSERT(maxchar <= 0xFFFF);
Victor Stinner77faf692011-11-20 18:56:05 +0100503 }
504 else {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200505 ASSERT(maxchar >= 0x10000);
506 ASSERT(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100507 }
Victor Stinner50fe3f82018-10-26 18:47:15 +0200508 ASSERT(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200509 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400510 return 1;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200511
512#undef ASSERT
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400513}
Victor Stinner910337b2011-10-03 03:20:16 +0200514#endif
515
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100516static PyObject*
517unicode_result_wchar(PyObject *unicode)
518{
519#ifndef Py_DEBUG
520 Py_ssize_t len;
521
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100522 len = _PyUnicode_WSTR_LENGTH(unicode);
523 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100524 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200525 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100526 }
527
528 if (len == 1) {
529 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100530 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100531 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
532 Py_DECREF(unicode);
533 return latin1_char;
534 }
535 }
536
537 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200538 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100539 return NULL;
540 }
541#else
Victor Stinneraa771272012-10-04 02:32:58 +0200542 assert(Py_REFCNT(unicode) == 1);
543
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100544 /* don't make the result ready in debug mode to ensure that the caller
545 makes the string ready before using it */
546 assert(_PyUnicode_CheckConsistency(unicode, 1));
547#endif
548 return unicode;
549}
550
551static PyObject*
552unicode_result_ready(PyObject *unicode)
553{
554 Py_ssize_t length;
555
556 length = PyUnicode_GET_LENGTH(unicode);
557 if (length == 0) {
558 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100559 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200560 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100561 }
562 return unicode_empty;
563 }
564
565 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200566 void *data = PyUnicode_DATA(unicode);
567 int kind = PyUnicode_KIND(unicode);
568 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100569 if (ch < 256) {
570 PyObject *latin1_char = unicode_latin1[ch];
571 if (latin1_char != NULL) {
572 if (unicode != latin1_char) {
573 Py_INCREF(latin1_char);
574 Py_DECREF(unicode);
575 }
576 return latin1_char;
577 }
578 else {
579 assert(_PyUnicode_CheckConsistency(unicode, 1));
580 Py_INCREF(unicode);
581 unicode_latin1[ch] = unicode;
582 return unicode;
583 }
584 }
585 }
586
587 assert(_PyUnicode_CheckConsistency(unicode, 1));
588 return unicode;
589}
590
591static PyObject*
592unicode_result(PyObject *unicode)
593{
594 assert(_PyUnicode_CHECK(unicode));
595 if (PyUnicode_IS_READY(unicode))
596 return unicode_result_ready(unicode);
597 else
598 return unicode_result_wchar(unicode);
599}
600
Victor Stinnerc4b49542011-12-11 22:44:26 +0100601static PyObject*
602unicode_result_unchanged(PyObject *unicode)
603{
604 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500605 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100606 return NULL;
607 Py_INCREF(unicode);
608 return unicode;
609 }
610 else
611 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100612 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100613}
614
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200615/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
616 ASCII, Latin1, UTF-8, etc. */
617static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200618backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200619 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
620{
Victor Stinnerad771582015-10-09 12:38:53 +0200621 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200622 Py_UCS4 ch;
623 enum PyUnicode_Kind kind;
624 void *data;
625
626 assert(PyUnicode_IS_READY(unicode));
627 kind = PyUnicode_KIND(unicode);
628 data = PyUnicode_DATA(unicode);
629
630 size = 0;
631 /* determine replacement size */
632 for (i = collstart; i < collend; ++i) {
633 Py_ssize_t incr;
634
635 ch = PyUnicode_READ(kind, data, i);
636 if (ch < 0x100)
637 incr = 2+2;
638 else if (ch < 0x10000)
639 incr = 2+4;
640 else {
641 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200642 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200643 }
644 if (size > PY_SSIZE_T_MAX - incr) {
645 PyErr_SetString(PyExc_OverflowError,
646 "encoded result is too long for a Python string");
647 return NULL;
648 }
649 size += incr;
650 }
651
Victor Stinnerad771582015-10-09 12:38:53 +0200652 str = _PyBytesWriter_Prepare(writer, str, size);
653 if (str == NULL)
654 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200655
656 /* generate replacement */
657 for (i = collstart; i < collend; ++i) {
658 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200659 *str++ = '\\';
660 if (ch >= 0x00010000) {
661 *str++ = 'U';
662 *str++ = Py_hexdigits[(ch>>28)&0xf];
663 *str++ = Py_hexdigits[(ch>>24)&0xf];
664 *str++ = Py_hexdigits[(ch>>20)&0xf];
665 *str++ = Py_hexdigits[(ch>>16)&0xf];
666 *str++ = Py_hexdigits[(ch>>12)&0xf];
667 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200668 }
Victor Stinner797485e2015-10-09 03:17:30 +0200669 else if (ch >= 0x100) {
670 *str++ = 'u';
671 *str++ = Py_hexdigits[(ch>>12)&0xf];
672 *str++ = Py_hexdigits[(ch>>8)&0xf];
673 }
674 else
675 *str++ = 'x';
676 *str++ = Py_hexdigits[(ch>>4)&0xf];
677 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200678 }
679 return str;
680}
681
682/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
683 ASCII, Latin1, UTF-8, etc. */
684static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200685xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200686 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
687{
Victor Stinnerad771582015-10-09 12:38:53 +0200688 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200689 Py_UCS4 ch;
690 enum PyUnicode_Kind kind;
691 void *data;
692
693 assert(PyUnicode_IS_READY(unicode));
694 kind = PyUnicode_KIND(unicode);
695 data = PyUnicode_DATA(unicode);
696
697 size = 0;
698 /* determine replacement size */
699 for (i = collstart; i < collend; ++i) {
700 Py_ssize_t incr;
701
702 ch = PyUnicode_READ(kind, data, i);
703 if (ch < 10)
704 incr = 2+1+1;
705 else if (ch < 100)
706 incr = 2+2+1;
707 else if (ch < 1000)
708 incr = 2+3+1;
709 else if (ch < 10000)
710 incr = 2+4+1;
711 else if (ch < 100000)
712 incr = 2+5+1;
713 else if (ch < 1000000)
714 incr = 2+6+1;
715 else {
716 assert(ch <= MAX_UNICODE);
717 incr = 2+7+1;
718 }
719 if (size > PY_SSIZE_T_MAX - incr) {
720 PyErr_SetString(PyExc_OverflowError,
721 "encoded result is too long for a Python string");
722 return NULL;
723 }
724 size += incr;
725 }
726
Victor Stinnerad771582015-10-09 12:38:53 +0200727 str = _PyBytesWriter_Prepare(writer, str, size);
728 if (str == NULL)
729 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200730
731 /* generate replacement */
732 for (i = collstart; i < collend; ++i) {
733 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
734 }
735 return str;
736}
737
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738/* --- Bloom Filters ----------------------------------------------------- */
739
740/* stuff to implement simple "bloom filters" for Unicode characters.
741 to keep things simple, we use a single bitmask, using the least 5
742 bits from each unicode characters as the bit index. */
743
744/* the linebreak mask is set up by Unicode_Init below */
745
Antoine Pitrouf068f942010-01-13 14:19:12 +0000746#if LONG_BIT >= 128
747#define BLOOM_WIDTH 128
748#elif LONG_BIT >= 64
749#define BLOOM_WIDTH 64
750#elif LONG_BIT >= 32
751#define BLOOM_WIDTH 32
752#else
753#error "LONG_BIT is smaller than 32"
754#endif
755
Thomas Wouters477c8d52006-05-27 19:21:47 +0000756#define BLOOM_MASK unsigned long
757
Serhiy Storchaka05997252013-01-26 12:14:02 +0200758static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759
Antoine Pitrouf068f942010-01-13 14:19:12 +0000760#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761
Benjamin Peterson29060642009-01-31 22:14:21 +0000762#define BLOOM_LINEBREAK(ch) \
763 ((ch) < 128U ? ascii_linebreak[(ch)] : \
764 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000765
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700766static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200767make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000768{
Victor Stinnera85af502013-04-09 21:53:54 +0200769#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
770 do { \
771 TYPE *data = (TYPE *)PTR; \
772 TYPE *end = data + LEN; \
773 Py_UCS4 ch; \
774 for (; data != end; data++) { \
775 ch = *data; \
776 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
777 } \
778 break; \
779 } while (0)
780
Thomas Wouters477c8d52006-05-27 19:21:47 +0000781 /* calculate simple bloom-style bitmask for a given unicode string */
782
Antoine Pitrouf068f942010-01-13 14:19:12 +0000783 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000784
785 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200786 switch (kind) {
787 case PyUnicode_1BYTE_KIND:
788 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
789 break;
790 case PyUnicode_2BYTE_KIND:
791 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
792 break;
793 case PyUnicode_4BYTE_KIND:
794 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
795 break;
796 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700797 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200798 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000799 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200800
801#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000802}
803
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300804static int
805ensure_unicode(PyObject *obj)
806{
807 if (!PyUnicode_Check(obj)) {
808 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +0200809 "must be str, not %.100s",
810 Py_TYPE(obj)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300811 return -1;
812 }
813 return PyUnicode_READY(obj);
814}
815
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200816/* Compilation of templated routines */
817
818#include "stringlib/asciilib.h"
819#include "stringlib/fastsearch.h"
820#include "stringlib/partition.h"
821#include "stringlib/split.h"
822#include "stringlib/count.h"
823#include "stringlib/find.h"
824#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200825#include "stringlib/undef.h"
826
827#include "stringlib/ucs1lib.h"
828#include "stringlib/fastsearch.h"
829#include "stringlib/partition.h"
830#include "stringlib/split.h"
831#include "stringlib/count.h"
832#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300833#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200834#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200835#include "stringlib/undef.h"
836
837#include "stringlib/ucs2lib.h"
838#include "stringlib/fastsearch.h"
839#include "stringlib/partition.h"
840#include "stringlib/split.h"
841#include "stringlib/count.h"
842#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300843#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200844#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200845#include "stringlib/undef.h"
846
847#include "stringlib/ucs4lib.h"
848#include "stringlib/fastsearch.h"
849#include "stringlib/partition.h"
850#include "stringlib/split.h"
851#include "stringlib/count.h"
852#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300853#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200854#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200855#include "stringlib/undef.h"
856
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200857#include "stringlib/unicodedefs.h"
858#include "stringlib/fastsearch.h"
859#include "stringlib/count.h"
860#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100861#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200862
Guido van Rossumd57fd912000-03-10 22:53:23 +0000863/* --- Unicode Object ----------------------------------------------------- */
864
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700865static inline Py_ssize_t
866findchar(const void *s, int kind,
867 Py_ssize_t size, Py_UCS4 ch,
868 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200869{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200870 switch (kind) {
871 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200872 if ((Py_UCS1) ch != ch)
873 return -1;
874 if (direction > 0)
875 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
876 else
877 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200878 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200879 if ((Py_UCS2) ch != ch)
880 return -1;
881 if (direction > 0)
882 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
883 else
884 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200885 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200886 if (direction > 0)
887 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
888 else
889 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200890 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700891 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200892 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200893}
894
Victor Stinnerafffce42012-10-03 23:03:17 +0200895#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000896/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200897 earlier.
898
899 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
900 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
901 invalid character in Unicode 6.0. */
902static void
903unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
904{
905 int kind = PyUnicode_KIND(unicode);
906 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
907 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
908 if (length <= old_length)
909 return;
910 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
911}
912#endif
913
Victor Stinnerfe226c02011-10-03 03:52:20 +0200914static PyObject*
915resize_compact(PyObject *unicode, Py_ssize_t length)
916{
917 Py_ssize_t char_size;
918 Py_ssize_t struct_size;
919 Py_ssize_t new_size;
920 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100921 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200922#ifdef Py_DEBUG
923 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
924#endif
925
Victor Stinner79891572012-05-03 13:43:07 +0200926 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200927 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100928 assert(PyUnicode_IS_COMPACT(unicode));
929
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200930 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100931 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200932 struct_size = sizeof(PyASCIIObject);
933 else
934 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200935 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200936
Victor Stinnerfe226c02011-10-03 03:52:20 +0200937 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
938 PyErr_NoMemory();
939 return NULL;
940 }
941 new_size = (struct_size + (length + 1) * char_size);
942
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200943 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
944 PyObject_DEL(_PyUnicode_UTF8(unicode));
945 _PyUnicode_UTF8(unicode) = NULL;
946 _PyUnicode_UTF8_LENGTH(unicode) = 0;
947 }
Victor Stinner84def372011-12-11 20:04:56 +0100948 _Py_DEC_REFTOTAL;
949 _Py_ForgetReference(unicode);
950
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300951 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100952 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100953 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200954 PyErr_NoMemory();
955 return NULL;
956 }
Victor Stinner84def372011-12-11 20:04:56 +0100957 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200958 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100959
Victor Stinnerfe226c02011-10-03 03:52:20 +0200960 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200961 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200962 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100963 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200964 _PyUnicode_WSTR_LENGTH(unicode) = length;
965 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100966 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
967 PyObject_DEL(_PyUnicode_WSTR(unicode));
968 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100969 if (!PyUnicode_IS_ASCII(unicode))
970 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100971 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200972#ifdef Py_DEBUG
973 unicode_fill_invalid(unicode, old_length);
974#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200975 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
976 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200977 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200978 return unicode;
979}
980
Alexander Belopolsky40018472011-02-26 01:02:56 +0000981static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200982resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000983{
Victor Stinner95663112011-10-04 01:03:50 +0200984 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100985 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200986 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200987 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000988
Victor Stinnerfe226c02011-10-03 03:52:20 +0200989 if (PyUnicode_IS_READY(unicode)) {
990 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200991 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200992 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200993#ifdef Py_DEBUG
994 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
995#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200996
997 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200998 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200999 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
1000 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001001
1002 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1003 PyErr_NoMemory();
1004 return -1;
1005 }
1006 new_size = (length + 1) * char_size;
1007
Victor Stinner7a9105a2011-12-12 00:13:42 +01001008 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1009 {
1010 PyObject_DEL(_PyUnicode_UTF8(unicode));
1011 _PyUnicode_UTF8(unicode) = NULL;
1012 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1013 }
1014
Victor Stinnerfe226c02011-10-03 03:52:20 +02001015 data = (PyObject *)PyObject_REALLOC(data, new_size);
1016 if (data == NULL) {
1017 PyErr_NoMemory();
1018 return -1;
1019 }
1020 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001021 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001022 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001023 _PyUnicode_WSTR_LENGTH(unicode) = length;
1024 }
1025 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001026 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001027 _PyUnicode_UTF8_LENGTH(unicode) = length;
1028 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001029 _PyUnicode_LENGTH(unicode) = length;
1030 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001031#ifdef Py_DEBUG
1032 unicode_fill_invalid(unicode, old_length);
1033#endif
Victor Stinner95663112011-10-04 01:03:50 +02001034 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001035 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001036 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001037 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001038 }
Victor Stinner95663112011-10-04 01:03:50 +02001039 assert(_PyUnicode_WSTR(unicode) != NULL);
1040
1041 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001042 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001043 PyErr_NoMemory();
1044 return -1;
1045 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001046 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001047 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001048 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001049 if (!wstr) {
1050 PyErr_NoMemory();
1051 return -1;
1052 }
1053 _PyUnicode_WSTR(unicode) = wstr;
1054 _PyUnicode_WSTR(unicode)[length] = 0;
1055 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001056 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001057 return 0;
1058}
1059
Victor Stinnerfe226c02011-10-03 03:52:20 +02001060static PyObject*
1061resize_copy(PyObject *unicode, Py_ssize_t length)
1062{
1063 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001064 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001065 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001066
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001067 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001068
1069 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1070 if (copy == NULL)
1071 return NULL;
1072
1073 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001074 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001075 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001076 }
1077 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001078 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001079
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001080 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001081 if (w == NULL)
1082 return NULL;
1083 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1084 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001085 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001086 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001087 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001088 }
1089}
1090
Guido van Rossumd57fd912000-03-10 22:53:23 +00001091/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001092 Ux0000 terminated; some code (e.g. new_identifier)
1093 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001094
1095 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001096 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001097
1098*/
1099
Alexander Belopolsky40018472011-02-26 01:02:56 +00001100static PyUnicodeObject *
1101_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001102{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001103 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001104 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001105
Thomas Wouters477c8d52006-05-27 19:21:47 +00001106 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001107 if (length == 0 && unicode_empty != NULL) {
1108 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001109 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001110 }
1111
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001112 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001113 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001114 return (PyUnicodeObject *)PyErr_NoMemory();
1115 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001116 if (length < 0) {
1117 PyErr_SetString(PyExc_SystemError,
1118 "Negative size passed to _PyUnicode_New");
1119 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001120 }
1121
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001122 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1123 if (unicode == NULL)
1124 return NULL;
1125 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001126
1127 _PyUnicode_WSTR_LENGTH(unicode) = length;
1128 _PyUnicode_HASH(unicode) = -1;
1129 _PyUnicode_STATE(unicode).interned = 0;
1130 _PyUnicode_STATE(unicode).kind = 0;
1131 _PyUnicode_STATE(unicode).compact = 0;
1132 _PyUnicode_STATE(unicode).ready = 0;
1133 _PyUnicode_STATE(unicode).ascii = 0;
1134 _PyUnicode_DATA_ANY(unicode) = NULL;
1135 _PyUnicode_LENGTH(unicode) = 0;
1136 _PyUnicode_UTF8(unicode) = NULL;
1137 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1138
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001139 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1140 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001141 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001142 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001143 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001144 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001145
Jeremy Hyltond8082792003-09-16 19:41:39 +00001146 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001147 * the caller fails before initializing str -- unicode_resize()
1148 * reads str[0], and the Keep-Alive optimization can keep memory
1149 * allocated for str alive across a call to unicode_dealloc(unicode).
1150 * We don't want unicode_resize to read uninitialized memory in
1151 * that case.
1152 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001153 _PyUnicode_WSTR(unicode)[0] = 0;
1154 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001155
Victor Stinner7931d9a2011-11-04 00:22:48 +01001156 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001157 return unicode;
1158}
1159
Victor Stinnerf42dc442011-10-02 23:33:16 +02001160static const char*
1161unicode_kind_name(PyObject *unicode)
1162{
Victor Stinner42dfd712011-10-03 14:41:45 +02001163 /* don't check consistency: unicode_kind_name() is called from
1164 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001165 if (!PyUnicode_IS_COMPACT(unicode))
1166 {
1167 if (!PyUnicode_IS_READY(unicode))
1168 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001169 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001170 {
1171 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001172 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001173 return "legacy ascii";
1174 else
1175 return "legacy latin1";
1176 case PyUnicode_2BYTE_KIND:
1177 return "legacy UCS2";
1178 case PyUnicode_4BYTE_KIND:
1179 return "legacy UCS4";
1180 default:
1181 return "<legacy invalid kind>";
1182 }
1183 }
1184 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001185 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001186 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001187 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001188 return "ascii";
1189 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001190 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001191 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001192 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001193 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001194 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001195 default:
1196 return "<invalid compact kind>";
1197 }
1198}
1199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001200#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001201/* Functions wrapping macros for use in debugger */
Victor Stinnera42de742018-11-22 10:25:22 +01001202char *_PyUnicode_utf8(void *unicode_raw){
1203 PyObject *unicode = _PyObject_CAST(unicode_raw);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001204 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001205}
1206
Victor Stinnera42de742018-11-22 10:25:22 +01001207void *_PyUnicode_compact_data(void *unicode_raw) {
1208 PyObject *unicode = _PyObject_CAST(unicode_raw);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209 return _PyUnicode_COMPACT_DATA(unicode);
1210}
Victor Stinnera42de742018-11-22 10:25:22 +01001211void *_PyUnicode_data(void *unicode_raw) {
1212 PyObject *unicode = _PyObject_CAST(unicode_raw);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001213 printf("obj %p\n", unicode);
1214 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1215 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1216 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1217 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1218 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1219 return PyUnicode_DATA(unicode);
1220}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001221
1222void
1223_PyUnicode_Dump(PyObject *op)
1224{
1225 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001226 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1227 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1228 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001229
Victor Stinnera849a4b2011-10-03 12:12:11 +02001230 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001231 {
1232 if (ascii->state.ascii)
1233 data = (ascii + 1);
1234 else
1235 data = (compact + 1);
1236 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001237 else
1238 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001239 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1240 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001241
Victor Stinnera849a4b2011-10-03 12:12:11 +02001242 if (ascii->wstr == data)
1243 printf("shared ");
1244 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001245
Victor Stinnera3b334d2011-10-03 13:53:37 +02001246 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001247 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001248 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1249 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001250 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1251 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001252 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001253 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001254}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001255#endif
1256
1257PyObject *
1258PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1259{
1260 PyObject *obj;
1261 PyCompactUnicodeObject *unicode;
1262 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001263 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001264 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001265 Py_ssize_t char_size;
1266 Py_ssize_t struct_size;
1267
1268 /* Optimization for empty strings */
1269 if (size == 0 && unicode_empty != NULL) {
1270 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001271 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001272 }
1273
Victor Stinner9e9d6892011-10-04 01:02:02 +02001274 is_ascii = 0;
1275 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 struct_size = sizeof(PyCompactUnicodeObject);
1277 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001278 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001279 char_size = 1;
1280 is_ascii = 1;
1281 struct_size = sizeof(PyASCIIObject);
1282 }
1283 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001284 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001285 char_size = 1;
1286 }
1287 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001288 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001289 char_size = 2;
1290 if (sizeof(wchar_t) == 2)
1291 is_sharing = 1;
1292 }
1293 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001294 if (maxchar > MAX_UNICODE) {
1295 PyErr_SetString(PyExc_SystemError,
1296 "invalid maximum character passed to PyUnicode_New");
1297 return NULL;
1298 }
Victor Stinner8f825062012-04-27 13:55:39 +02001299 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001300 char_size = 4;
1301 if (sizeof(wchar_t) == 4)
1302 is_sharing = 1;
1303 }
1304
1305 /* Ensure we won't overflow the size. */
1306 if (size < 0) {
1307 PyErr_SetString(PyExc_SystemError,
1308 "Negative size passed to PyUnicode_New");
1309 return NULL;
1310 }
1311 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1312 return PyErr_NoMemory();
1313
1314 /* Duplicated allocation code from _PyObject_New() instead of a call to
1315 * PyObject_New() so we are able to allocate space for the object and
1316 * it's data buffer.
1317 */
1318 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1319 if (obj == NULL)
1320 return PyErr_NoMemory();
1321 obj = PyObject_INIT(obj, &PyUnicode_Type);
1322 if (obj == NULL)
1323 return NULL;
1324
1325 unicode = (PyCompactUnicodeObject *)obj;
1326 if (is_ascii)
1327 data = ((PyASCIIObject*)obj) + 1;
1328 else
1329 data = unicode + 1;
1330 _PyUnicode_LENGTH(unicode) = size;
1331 _PyUnicode_HASH(unicode) = -1;
1332 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001333 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001334 _PyUnicode_STATE(unicode).compact = 1;
1335 _PyUnicode_STATE(unicode).ready = 1;
1336 _PyUnicode_STATE(unicode).ascii = is_ascii;
1337 if (is_ascii) {
1338 ((char*)data)[size] = 0;
1339 _PyUnicode_WSTR(unicode) = NULL;
1340 }
Victor Stinner8f825062012-04-27 13:55:39 +02001341 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 ((char*)data)[size] = 0;
1343 _PyUnicode_WSTR(unicode) = NULL;
1344 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001345 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001346 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001347 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001348 else {
1349 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001350 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001351 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001352 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001353 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354 ((Py_UCS4*)data)[size] = 0;
1355 if (is_sharing) {
1356 _PyUnicode_WSTR_LENGTH(unicode) = size;
1357 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1358 }
1359 else {
1360 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1361 _PyUnicode_WSTR(unicode) = NULL;
1362 }
1363 }
Victor Stinner8f825062012-04-27 13:55:39 +02001364#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001365 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001366#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001367 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 return obj;
1369}
1370
1371#if SIZEOF_WCHAR_T == 2
1372/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1373 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001374 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001375
1376 This function assumes that unicode can hold one more code point than wstr
1377 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001378static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001379unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001380 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381{
1382 const wchar_t *iter;
1383 Py_UCS4 *ucs4_out;
1384
Victor Stinner910337b2011-10-03 03:20:16 +02001385 assert(unicode != NULL);
1386 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001387 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1388 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1389
1390 for (iter = begin; iter < end; ) {
1391 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1392 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001393 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1394 && (iter+1) < end
1395 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 {
Victor Stinner551ac952011-11-29 22:58:13 +01001397 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001398 iter += 2;
1399 }
1400 else {
1401 *ucs4_out++ = *iter;
1402 iter++;
1403 }
1404 }
1405 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1406 _PyUnicode_GET_LENGTH(unicode)));
1407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001408}
1409#endif
1410
Victor Stinnercd9950f2011-10-02 00:34:53 +02001411static int
Victor Stinner488fa492011-12-12 00:01:39 +01001412unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001413{
Victor Stinner488fa492011-12-12 00:01:39 +01001414 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001415 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001416 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001417 return -1;
1418 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001419 return 0;
1420}
1421
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001422static int
1423_copy_characters(PyObject *to, Py_ssize_t to_start,
1424 PyObject *from, Py_ssize_t from_start,
1425 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001426{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001427 unsigned int from_kind, to_kind;
1428 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001429
Victor Stinneree4544c2012-05-09 22:24:08 +02001430 assert(0 <= how_many);
1431 assert(0 <= from_start);
1432 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001433 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001434 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001435 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001436
Victor Stinnerd3f08822012-05-29 12:57:52 +02001437 assert(PyUnicode_Check(to));
1438 assert(PyUnicode_IS_READY(to));
1439 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1440
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001441 if (how_many == 0)
1442 return 0;
1443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001444 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001445 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001446 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001447 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001448
Victor Stinnerf1852262012-06-16 16:38:26 +02001449#ifdef Py_DEBUG
1450 if (!check_maxchar
1451 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1452 {
1453 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1454 Py_UCS4 ch;
1455 Py_ssize_t i;
1456 for (i=0; i < how_many; i++) {
1457 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1458 assert(ch <= to_maxchar);
1459 }
1460 }
1461#endif
1462
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001463 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001464 if (check_maxchar
1465 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1466 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001467 /* Writing Latin-1 characters into an ASCII string requires to
1468 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001469 Py_UCS4 max_char;
1470 max_char = ucs1lib_find_max_char(from_data,
1471 (Py_UCS1*)from_data + how_many);
1472 if (max_char >= 128)
1473 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001474 }
Christian Heimesf051e432016-09-13 20:22:02 +02001475 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001476 (char*)from_data + from_kind * from_start,
1477 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001478 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001479 else if (from_kind == PyUnicode_1BYTE_KIND
1480 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001481 {
1482 _PyUnicode_CONVERT_BYTES(
1483 Py_UCS1, Py_UCS2,
1484 PyUnicode_1BYTE_DATA(from) + from_start,
1485 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1486 PyUnicode_2BYTE_DATA(to) + to_start
1487 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001488 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001489 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001490 && to_kind == PyUnicode_4BYTE_KIND)
1491 {
1492 _PyUnicode_CONVERT_BYTES(
1493 Py_UCS1, Py_UCS4,
1494 PyUnicode_1BYTE_DATA(from) + from_start,
1495 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1496 PyUnicode_4BYTE_DATA(to) + to_start
1497 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001498 }
1499 else if (from_kind == PyUnicode_2BYTE_KIND
1500 && to_kind == PyUnicode_4BYTE_KIND)
1501 {
1502 _PyUnicode_CONVERT_BYTES(
1503 Py_UCS2, Py_UCS4,
1504 PyUnicode_2BYTE_DATA(from) + from_start,
1505 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1506 PyUnicode_4BYTE_DATA(to) + to_start
1507 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001508 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001509 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001510 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1511
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001512 if (!check_maxchar) {
1513 if (from_kind == PyUnicode_2BYTE_KIND
1514 && to_kind == PyUnicode_1BYTE_KIND)
1515 {
1516 _PyUnicode_CONVERT_BYTES(
1517 Py_UCS2, Py_UCS1,
1518 PyUnicode_2BYTE_DATA(from) + from_start,
1519 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1520 PyUnicode_1BYTE_DATA(to) + to_start
1521 );
1522 }
1523 else if (from_kind == PyUnicode_4BYTE_KIND
1524 && to_kind == PyUnicode_1BYTE_KIND)
1525 {
1526 _PyUnicode_CONVERT_BYTES(
1527 Py_UCS4, Py_UCS1,
1528 PyUnicode_4BYTE_DATA(from) + from_start,
1529 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1530 PyUnicode_1BYTE_DATA(to) + to_start
1531 );
1532 }
1533 else if (from_kind == PyUnicode_4BYTE_KIND
1534 && to_kind == PyUnicode_2BYTE_KIND)
1535 {
1536 _PyUnicode_CONVERT_BYTES(
1537 Py_UCS4, Py_UCS2,
1538 PyUnicode_4BYTE_DATA(from) + from_start,
1539 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1540 PyUnicode_2BYTE_DATA(to) + to_start
1541 );
1542 }
1543 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001544 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001545 }
1546 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001547 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001548 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001549 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001550 Py_ssize_t i;
1551
Victor Stinnera0702ab2011-09-29 14:14:38 +02001552 for (i=0; i < how_many; i++) {
1553 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001554 if (ch > to_maxchar)
1555 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001556 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1557 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001558 }
1559 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001560 return 0;
1561}
1562
Victor Stinnerd3f08822012-05-29 12:57:52 +02001563void
1564_PyUnicode_FastCopyCharacters(
1565 PyObject *to, Py_ssize_t to_start,
1566 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001567{
1568 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1569}
1570
1571Py_ssize_t
1572PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1573 PyObject *from, Py_ssize_t from_start,
1574 Py_ssize_t how_many)
1575{
1576 int err;
1577
1578 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1579 PyErr_BadInternalCall();
1580 return -1;
1581 }
1582
Benjamin Petersonbac79492012-01-14 13:34:47 -05001583 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001584 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001585 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001586 return -1;
1587
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001588 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001589 PyErr_SetString(PyExc_IndexError, "string index out of range");
1590 return -1;
1591 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001592 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001593 PyErr_SetString(PyExc_IndexError, "string index out of range");
1594 return -1;
1595 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001596 if (how_many < 0) {
1597 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1598 return -1;
1599 }
1600 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001601 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1602 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001603 "Cannot write %zi characters at %zi "
1604 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001605 how_many, to_start, PyUnicode_GET_LENGTH(to));
1606 return -1;
1607 }
1608
1609 if (how_many == 0)
1610 return 0;
1611
Victor Stinner488fa492011-12-12 00:01:39 +01001612 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001613 return -1;
1614
1615 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1616 if (err) {
1617 PyErr_Format(PyExc_SystemError,
1618 "Cannot copy %s characters "
1619 "into a string of %s characters",
1620 unicode_kind_name(from),
1621 unicode_kind_name(to));
1622 return -1;
1623 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001624 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001625}
1626
Victor Stinner17222162011-09-28 22:15:37 +02001627/* Find the maximum code point and count the number of surrogate pairs so a
1628 correct string length can be computed before converting a string to UCS4.
1629 This function counts single surrogates as a character and not as a pair.
1630
1631 Return 0 on success, or -1 on error. */
1632static int
1633find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1634 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635{
1636 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001637 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638
Victor Stinnerc53be962011-10-02 21:33:54 +02001639 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001640 *num_surrogates = 0;
1641 *maxchar = 0;
1642
1643 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001644#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001645 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1646 && (iter+1) < end
1647 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1648 {
1649 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1650 ++(*num_surrogates);
1651 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001652 }
1653 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001654#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001655 {
1656 ch = *iter;
1657 iter++;
1658 }
1659 if (ch > *maxchar) {
1660 *maxchar = ch;
1661 if (*maxchar > MAX_UNICODE) {
1662 PyErr_Format(PyExc_ValueError,
1663 "character U+%x is not in range [U+0000; U+10ffff]",
1664 ch);
1665 return -1;
1666 }
1667 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001668 }
1669 return 0;
1670}
1671
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001672int
1673_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001674{
1675 wchar_t *end;
1676 Py_UCS4 maxchar = 0;
1677 Py_ssize_t num_surrogates;
1678#if SIZEOF_WCHAR_T == 2
1679 Py_ssize_t length_wo_surrogates;
1680#endif
1681
Georg Brandl7597add2011-10-05 16:36:47 +02001682 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001683 strings were created using _PyObject_New() and where no canonical
1684 representation (the str field) has been set yet aka strings
1685 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001686 assert(_PyUnicode_CHECK(unicode));
1687 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001688 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001689 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001690 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001691 /* Actually, it should neither be interned nor be anything else: */
1692 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001694 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001695 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001696 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001697 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001698
1699 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001700 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1701 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001702 PyErr_NoMemory();
1703 return -1;
1704 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001705 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001706 _PyUnicode_WSTR(unicode), end,
1707 PyUnicode_1BYTE_DATA(unicode));
1708 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1709 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1710 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1711 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001712 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001713 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001714 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001715 }
1716 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001717 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001718 _PyUnicode_UTF8(unicode) = NULL;
1719 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001720 }
1721 PyObject_FREE(_PyUnicode_WSTR(unicode));
1722 _PyUnicode_WSTR(unicode) = NULL;
1723 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1724 }
1725 /* In this case we might have to convert down from 4-byte native
1726 wchar_t to 2-byte unicode. */
1727 else if (maxchar < 65536) {
1728 assert(num_surrogates == 0 &&
1729 "FindMaxCharAndNumSurrogatePairs() messed up");
1730
Victor Stinner506f5922011-09-28 22:34:18 +02001731#if SIZEOF_WCHAR_T == 2
1732 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001733 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001734 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1735 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1736 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001737 _PyUnicode_UTF8(unicode) = NULL;
1738 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001739#else
1740 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001741 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001742 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001743 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001744 PyErr_NoMemory();
1745 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001746 }
Victor Stinner506f5922011-09-28 22:34:18 +02001747 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1748 _PyUnicode_WSTR(unicode), end,
1749 PyUnicode_2BYTE_DATA(unicode));
1750 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1751 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1752 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001753 _PyUnicode_UTF8(unicode) = NULL;
1754 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001755 PyObject_FREE(_PyUnicode_WSTR(unicode));
1756 _PyUnicode_WSTR(unicode) = NULL;
1757 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1758#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759 }
1760 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1761 else {
1762#if SIZEOF_WCHAR_T == 2
1763 /* in case the native representation is 2-bytes, we need to allocate a
1764 new normalized 4-byte version. */
1765 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001766 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1767 PyErr_NoMemory();
1768 return -1;
1769 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001770 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1771 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001772 PyErr_NoMemory();
1773 return -1;
1774 }
1775 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1776 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001777 _PyUnicode_UTF8(unicode) = NULL;
1778 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001779 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1780 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001781 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001782 PyObject_FREE(_PyUnicode_WSTR(unicode));
1783 _PyUnicode_WSTR(unicode) = NULL;
1784 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1785#else
1786 assert(num_surrogates == 0);
1787
Victor Stinnerc3c74152011-10-02 20:39:55 +02001788 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001789 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001790 _PyUnicode_UTF8(unicode) = NULL;
1791 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001792 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1793#endif
1794 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1795 }
1796 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001797 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001798 return 0;
1799}
1800
Alexander Belopolsky40018472011-02-26 01:02:56 +00001801static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001802unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001803{
Walter Dörwald16807132007-05-25 13:52:07 +00001804 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001805 case SSTATE_NOT_INTERNED:
1806 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001807
Benjamin Peterson29060642009-01-31 22:14:21 +00001808 case SSTATE_INTERNED_MORTAL:
1809 /* revive dead object temporarily for DelItem */
1810 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001811 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001812 Py_FatalError(
1813 "deletion of interned string failed");
1814 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001815
Benjamin Peterson29060642009-01-31 22:14:21 +00001816 case SSTATE_INTERNED_IMMORTAL:
1817 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001818 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001819
Benjamin Peterson29060642009-01-31 22:14:21 +00001820 default:
1821 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001822 }
1823
Victor Stinner03490912011-10-03 23:45:12 +02001824 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001825 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001826 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001827 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001828 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1829 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001830
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001831 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001832}
1833
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001834#ifdef Py_DEBUG
1835static int
1836unicode_is_singleton(PyObject *unicode)
1837{
1838 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1839 if (unicode == unicode_empty)
1840 return 1;
1841 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1842 {
1843 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1844 if (ch < 256 && unicode_latin1[ch] == unicode)
1845 return 1;
1846 }
1847 return 0;
1848}
1849#endif
1850
Alexander Belopolsky40018472011-02-26 01:02:56 +00001851static int
Victor Stinner488fa492011-12-12 00:01:39 +01001852unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001853{
Victor Stinner488fa492011-12-12 00:01:39 +01001854 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001855 if (Py_REFCNT(unicode) != 1)
1856 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001857 if (_PyUnicode_HASH(unicode) != -1)
1858 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001859 if (PyUnicode_CHECK_INTERNED(unicode))
1860 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001861 if (!PyUnicode_CheckExact(unicode))
1862 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001863#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001864 /* singleton refcount is greater than 1 */
1865 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001866#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001867 return 1;
1868}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001869
Victor Stinnerfe226c02011-10-03 03:52:20 +02001870static int
1871unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1872{
1873 PyObject *unicode;
1874 Py_ssize_t old_length;
1875
1876 assert(p_unicode != NULL);
1877 unicode = *p_unicode;
1878
1879 assert(unicode != NULL);
1880 assert(PyUnicode_Check(unicode));
1881 assert(0 <= length);
1882
Victor Stinner910337b2011-10-03 03:20:16 +02001883 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001884 old_length = PyUnicode_WSTR_LENGTH(unicode);
1885 else
1886 old_length = PyUnicode_GET_LENGTH(unicode);
1887 if (old_length == length)
1888 return 0;
1889
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001890 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001891 _Py_INCREF_UNICODE_EMPTY();
1892 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001893 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001894 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001895 return 0;
1896 }
1897
Victor Stinner488fa492011-12-12 00:01:39 +01001898 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001899 PyObject *copy = resize_copy(unicode, length);
1900 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001901 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001902 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001903 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001904 }
1905
Victor Stinnerfe226c02011-10-03 03:52:20 +02001906 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001907 PyObject *new_unicode = resize_compact(unicode, length);
1908 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001909 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001910 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001911 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001912 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001913 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001914}
1915
Alexander Belopolsky40018472011-02-26 01:02:56 +00001916int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001917PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001918{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001919 PyObject *unicode;
1920 if (p_unicode == NULL) {
1921 PyErr_BadInternalCall();
1922 return -1;
1923 }
1924 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001925 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001926 {
1927 PyErr_BadInternalCall();
1928 return -1;
1929 }
1930 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001931}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001932
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001933/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001934
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001935 WARNING: The function doesn't copy the terminating null character and
1936 doesn't check the maximum character (may write a latin1 character in an
1937 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001938static void
1939unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1940 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001941{
1942 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1943 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001944 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001945
1946 switch (kind) {
1947 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001948 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001949#ifdef Py_DEBUG
1950 if (PyUnicode_IS_ASCII(unicode)) {
1951 Py_UCS4 maxchar = ucs1lib_find_max_char(
1952 (const Py_UCS1*)str,
1953 (const Py_UCS1*)str + len);
1954 assert(maxchar < 128);
1955 }
1956#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001957 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001958 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001959 }
1960 case PyUnicode_2BYTE_KIND: {
1961 Py_UCS2 *start = (Py_UCS2 *)data + index;
1962 Py_UCS2 *ucs2 = start;
1963 assert(index <= PyUnicode_GET_LENGTH(unicode));
1964
Victor Stinner184252a2012-06-16 02:57:41 +02001965 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001966 *ucs2 = (Py_UCS2)*str;
1967
1968 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001969 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001970 }
1971 default: {
1972 Py_UCS4 *start = (Py_UCS4 *)data + index;
1973 Py_UCS4 *ucs4 = start;
1974 assert(kind == PyUnicode_4BYTE_KIND);
1975 assert(index <= PyUnicode_GET_LENGTH(unicode));
1976
Victor Stinner184252a2012-06-16 02:57:41 +02001977 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001978 *ucs4 = (Py_UCS4)*str;
1979
1980 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001981 }
1982 }
1983}
1984
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985static PyObject*
1986get_latin1_char(unsigned char ch)
1987{
Victor Stinnera464fc12011-10-02 20:39:30 +02001988 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001989 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001990 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001991 if (!unicode)
1992 return NULL;
1993 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001994 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001995 unicode_latin1[ch] = unicode;
1996 }
1997 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001998 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999}
2000
Victor Stinner985a82a2014-01-03 12:53:47 +01002001static PyObject*
2002unicode_char(Py_UCS4 ch)
2003{
2004 PyObject *unicode;
2005
2006 assert(ch <= MAX_UNICODE);
2007
Victor Stinnerf3b46b42014-01-03 13:16:00 +01002008 if (ch < 256)
2009 return get_latin1_char(ch);
2010
Victor Stinner985a82a2014-01-03 12:53:47 +01002011 unicode = PyUnicode_New(1, ch);
2012 if (unicode == NULL)
2013 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002014
2015 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
2016 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01002017 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002018 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01002019 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
2020 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
2021 }
2022 assert(_PyUnicode_CheckConsistency(unicode, 1));
2023 return unicode;
2024}
2025
Alexander Belopolsky40018472011-02-26 01:02:56 +00002026PyObject *
2027PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002028{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002029 if (u == NULL)
2030 return (PyObject*)_PyUnicode_New(size);
2031
2032 if (size < 0) {
2033 PyErr_BadInternalCall();
2034 return NULL;
2035 }
2036
2037 return PyUnicode_FromWideChar(u, size);
2038}
2039
2040PyObject *
2041PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2042{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002043 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002044 Py_UCS4 maxchar = 0;
2045 Py_ssize_t num_surrogates;
2046
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002047 if (u == NULL && size != 0) {
2048 PyErr_BadInternalCall();
2049 return NULL;
2050 }
2051
2052 if (size == -1) {
2053 size = wcslen(u);
2054 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002055
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002056 /* If the Unicode data is known at construction time, we can apply
2057 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002060 if (size == 0)
2061 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002062
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 /* Single character Unicode objects in the Latin-1 range are
2064 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002065 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002066 return get_latin1_char((unsigned char)*u);
2067
2068 /* If not empty and not single character, copy the Unicode data
2069 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002070 if (find_maxchar_surrogates(u, u + size,
2071 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002072 return NULL;
2073
Victor Stinner8faf8212011-12-08 22:14:11 +01002074 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002075 if (!unicode)
2076 return NULL;
2077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 switch (PyUnicode_KIND(unicode)) {
2079 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002080 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2082 break;
2083 case PyUnicode_2BYTE_KIND:
2084#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002085 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002086#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002087 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002088 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2089#endif
2090 break;
2091 case PyUnicode_4BYTE_KIND:
2092#if SIZEOF_WCHAR_T == 2
2093 /* This is the only case which has to process surrogates, thus
2094 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002095 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002096#else
2097 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002098 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002099#endif
2100 break;
2101 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002102 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002103 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002104
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002105 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002106}
2107
Alexander Belopolsky40018472011-02-26 01:02:56 +00002108PyObject *
2109PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002110{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002111 if (size < 0) {
2112 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002113 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002114 return NULL;
2115 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002116 if (u != NULL)
2117 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2118 else
2119 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002120}
2121
Alexander Belopolsky40018472011-02-26 01:02:56 +00002122PyObject *
2123PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002124{
2125 size_t size = strlen(u);
2126 if (size > PY_SSIZE_T_MAX) {
2127 PyErr_SetString(PyExc_OverflowError, "input too long");
2128 return NULL;
2129 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002130 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002131}
2132
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002133PyObject *
2134_PyUnicode_FromId(_Py_Identifier *id)
2135{
2136 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002137 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2138 strlen(id->string),
2139 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002140 if (!id->object)
2141 return NULL;
2142 PyUnicode_InternInPlace(&id->object);
2143 assert(!id->next);
2144 id->next = static_strings;
2145 static_strings = id;
2146 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002147 return id->object;
2148}
2149
2150void
2151_PyUnicode_ClearStaticStrings()
2152{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002153 _Py_Identifier *tmp, *s = static_strings;
2154 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002155 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002156 tmp = s->next;
2157 s->next = NULL;
2158 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002159 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002160 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002161}
2162
Benjamin Peterson0df54292012-03-26 14:50:32 -04002163/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002164
Victor Stinnerd3f08822012-05-29 12:57:52 +02002165PyObject*
2166_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002167{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002168 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002169 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002170 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002171#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002172 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002173#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002174 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002175 }
Victor Stinner785938e2011-12-11 20:09:03 +01002176 unicode = PyUnicode_New(size, 127);
2177 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002178 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002179 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2180 assert(_PyUnicode_CheckConsistency(unicode, 1));
2181 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002182}
2183
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002184static Py_UCS4
2185kind_maxchar_limit(unsigned int kind)
2186{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002187 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002188 case PyUnicode_1BYTE_KIND:
2189 return 0x80;
2190 case PyUnicode_2BYTE_KIND:
2191 return 0x100;
2192 case PyUnicode_4BYTE_KIND:
2193 return 0x10000;
2194 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002195 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002196 }
2197}
2198
Victor Stinner702c7342011-10-05 13:50:52 +02002199static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002200_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002201{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002202 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002203 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002204
Serhiy Storchaka678db842013-01-26 12:16:36 +02002205 if (size == 0)
2206 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002207 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002208 if (size == 1)
2209 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002210
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002211 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002212 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002213 if (!res)
2214 return NULL;
2215 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002216 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002218}
2219
Victor Stinnere57b1c02011-09-28 22:20:48 +02002220static PyObject*
2221_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002222{
2223 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002224 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002225
Serhiy Storchaka678db842013-01-26 12:16:36 +02002226 if (size == 0)
2227 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002228 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002229 if (size == 1)
2230 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002231
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002232 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002233 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002234 if (!res)
2235 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002236 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002237 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002238 else {
2239 _PyUnicode_CONVERT_BYTES(
2240 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2241 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002242 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002243 return res;
2244}
2245
Victor Stinnere57b1c02011-09-28 22:20:48 +02002246static PyObject*
2247_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002248{
2249 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002250 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002251
Serhiy Storchaka678db842013-01-26 12:16:36 +02002252 if (size == 0)
2253 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002254 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002255 if (size == 1)
2256 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002257
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002258 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002259 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002260 if (!res)
2261 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002262 if (max_char < 256)
2263 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2264 PyUnicode_1BYTE_DATA(res));
2265 else if (max_char < 0x10000)
2266 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2267 PyUnicode_2BYTE_DATA(res));
2268 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002269 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002270 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002271 return res;
2272}
2273
2274PyObject*
2275PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2276{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002277 if (size < 0) {
2278 PyErr_SetString(PyExc_ValueError, "size must be positive");
2279 return NULL;
2280 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002281 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002282 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002283 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002284 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002285 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002286 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002287 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002288 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002289 PyErr_SetString(PyExc_SystemError, "invalid kind");
2290 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002291 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002292}
2293
Victor Stinnerece58de2012-04-23 23:36:38 +02002294Py_UCS4
2295_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2296{
2297 enum PyUnicode_Kind kind;
2298 void *startptr, *endptr;
2299
2300 assert(PyUnicode_IS_READY(unicode));
2301 assert(0 <= start);
2302 assert(end <= PyUnicode_GET_LENGTH(unicode));
2303 assert(start <= end);
2304
2305 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2306 return PyUnicode_MAX_CHAR_VALUE(unicode);
2307
2308 if (start == end)
2309 return 127;
2310
Victor Stinner94d558b2012-04-27 22:26:58 +02002311 if (PyUnicode_IS_ASCII(unicode))
2312 return 127;
2313
Victor Stinnerece58de2012-04-23 23:36:38 +02002314 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002315 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002316 endptr = (char *)startptr + end * kind;
2317 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002318 switch(kind) {
2319 case PyUnicode_1BYTE_KIND:
2320 return ucs1lib_find_max_char(startptr, endptr);
2321 case PyUnicode_2BYTE_KIND:
2322 return ucs2lib_find_max_char(startptr, endptr);
2323 case PyUnicode_4BYTE_KIND:
2324 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002325 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002326 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002327 }
2328}
2329
Victor Stinner25a4b292011-10-06 12:31:55 +02002330/* Ensure that a string uses the most efficient storage, if it is not the
2331 case: create a new string with of the right kind. Write NULL into *p_unicode
2332 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002333static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002334unicode_adjust_maxchar(PyObject **p_unicode)
2335{
2336 PyObject *unicode, *copy;
2337 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002338 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002339 unsigned int kind;
2340
2341 assert(p_unicode != NULL);
2342 unicode = *p_unicode;
2343 assert(PyUnicode_IS_READY(unicode));
2344 if (PyUnicode_IS_ASCII(unicode))
2345 return;
2346
2347 len = PyUnicode_GET_LENGTH(unicode);
2348 kind = PyUnicode_KIND(unicode);
2349 if (kind == PyUnicode_1BYTE_KIND) {
2350 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002351 max_char = ucs1lib_find_max_char(u, u + len);
2352 if (max_char >= 128)
2353 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002354 }
2355 else if (kind == PyUnicode_2BYTE_KIND) {
2356 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002357 max_char = ucs2lib_find_max_char(u, u + len);
2358 if (max_char >= 256)
2359 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002360 }
2361 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002362 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002363 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002364 max_char = ucs4lib_find_max_char(u, u + len);
2365 if (max_char >= 0x10000)
2366 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002367 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002368 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002369 if (copy != NULL)
2370 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002371 Py_DECREF(unicode);
2372 *p_unicode = copy;
2373}
2374
Victor Stinner034f6cf2011-09-30 02:26:44 +02002375PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002376_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002377{
Victor Stinner87af4f22011-11-21 23:03:47 +01002378 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002379 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002380
Victor Stinner034f6cf2011-09-30 02:26:44 +02002381 if (!PyUnicode_Check(unicode)) {
2382 PyErr_BadInternalCall();
2383 return NULL;
2384 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002385 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002386 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002387
Victor Stinner87af4f22011-11-21 23:03:47 +01002388 length = PyUnicode_GET_LENGTH(unicode);
2389 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002390 if (!copy)
2391 return NULL;
2392 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2393
Christian Heimesf051e432016-09-13 20:22:02 +02002394 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002395 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002396 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002397 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002398}
2399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002400
Victor Stinnerbc603d12011-10-02 01:00:40 +02002401/* Widen Unicode objects to larger buffers. Don't write terminating null
2402 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403
2404void*
2405_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2406{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002407 Py_ssize_t len;
2408 void *result;
2409 unsigned int skind;
2410
Benjamin Petersonbac79492012-01-14 13:34:47 -05002411 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002412 return NULL;
2413
2414 len = PyUnicode_GET_LENGTH(s);
2415 skind = PyUnicode_KIND(s);
2416 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002417 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 return NULL;
2419 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002420 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002421 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002422 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002423 if (!result)
2424 return PyErr_NoMemory();
2425 assert(skind == PyUnicode_1BYTE_KIND);
2426 _PyUnicode_CONVERT_BYTES(
2427 Py_UCS1, Py_UCS2,
2428 PyUnicode_1BYTE_DATA(s),
2429 PyUnicode_1BYTE_DATA(s) + len,
2430 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002432 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002433 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002434 if (!result)
2435 return PyErr_NoMemory();
2436 if (skind == PyUnicode_2BYTE_KIND) {
2437 _PyUnicode_CONVERT_BYTES(
2438 Py_UCS2, Py_UCS4,
2439 PyUnicode_2BYTE_DATA(s),
2440 PyUnicode_2BYTE_DATA(s) + len,
2441 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002443 else {
2444 assert(skind == PyUnicode_1BYTE_KIND);
2445 _PyUnicode_CONVERT_BYTES(
2446 Py_UCS1, Py_UCS4,
2447 PyUnicode_1BYTE_DATA(s),
2448 PyUnicode_1BYTE_DATA(s) + len,
2449 result);
2450 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002451 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002452 default:
2453 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002454 }
Victor Stinner01698042011-10-04 00:04:26 +02002455 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002456 return NULL;
2457}
2458
2459static Py_UCS4*
2460as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2461 int copy_null)
2462{
2463 int kind;
2464 void *data;
2465 Py_ssize_t len, targetlen;
2466 if (PyUnicode_READY(string) == -1)
2467 return NULL;
2468 kind = PyUnicode_KIND(string);
2469 data = PyUnicode_DATA(string);
2470 len = PyUnicode_GET_LENGTH(string);
2471 targetlen = len;
2472 if (copy_null)
2473 targetlen++;
2474 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002475 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002476 if (!target) {
2477 PyErr_NoMemory();
2478 return NULL;
2479 }
2480 }
2481 else {
2482 if (targetsize < targetlen) {
2483 PyErr_Format(PyExc_SystemError,
2484 "string is longer than the buffer");
2485 if (copy_null && 0 < targetsize)
2486 target[0] = 0;
2487 return NULL;
2488 }
2489 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002490 if (kind == PyUnicode_1BYTE_KIND) {
2491 Py_UCS1 *start = (Py_UCS1 *) data;
2492 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002493 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002494 else if (kind == PyUnicode_2BYTE_KIND) {
2495 Py_UCS2 *start = (Py_UCS2 *) data;
2496 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2497 }
2498 else {
2499 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002500 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002501 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002502 if (copy_null)
2503 target[len] = 0;
2504 return target;
2505}
2506
2507Py_UCS4*
2508PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2509 int copy_null)
2510{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002511 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002512 PyErr_BadInternalCall();
2513 return NULL;
2514 }
2515 return as_ucs4(string, target, targetsize, copy_null);
2516}
2517
2518Py_UCS4*
2519PyUnicode_AsUCS4Copy(PyObject *string)
2520{
2521 return as_ucs4(string, NULL, 0, 1);
2522}
2523
Victor Stinner15a11362012-10-06 23:48:20 +02002524/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002525 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2526 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2527#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002528
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002529static int
2530unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2531 Py_ssize_t width, Py_ssize_t precision)
2532{
2533 Py_ssize_t length, fill, arglen;
2534 Py_UCS4 maxchar;
2535
2536 if (PyUnicode_READY(str) == -1)
2537 return -1;
2538
2539 length = PyUnicode_GET_LENGTH(str);
2540 if ((precision == -1 || precision >= length)
2541 && width <= length)
2542 return _PyUnicodeWriter_WriteStr(writer, str);
2543
2544 if (precision != -1)
2545 length = Py_MIN(precision, length);
2546
2547 arglen = Py_MAX(length, width);
2548 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2549 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2550 else
2551 maxchar = writer->maxchar;
2552
2553 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2554 return -1;
2555
2556 if (width > length) {
2557 fill = width - length;
2558 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2559 return -1;
2560 writer->pos += fill;
2561 }
2562
2563 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2564 str, 0, length);
2565 writer->pos += length;
2566 return 0;
2567}
2568
2569static int
Victor Stinner998b8062018-09-12 00:23:25 +02002570unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002571 Py_ssize_t width, Py_ssize_t precision)
2572{
2573 /* UTF-8 */
2574 Py_ssize_t length;
2575 PyObject *unicode;
2576 int res;
2577
2578 length = strlen(str);
2579 if (precision != -1)
2580 length = Py_MIN(length, precision);
2581 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2582 if (unicode == NULL)
2583 return -1;
2584
2585 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2586 Py_DECREF(unicode);
2587 return res;
2588}
2589
Victor Stinner96865452011-03-01 23:44:09 +00002590static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002591unicode_fromformat_arg(_PyUnicodeWriter *writer,
2592 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002593{
Victor Stinnere215d962012-10-06 23:03:36 +02002594 const char *p;
2595 Py_ssize_t len;
2596 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002597 Py_ssize_t width;
2598 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002599 int longflag;
2600 int longlongflag;
2601 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002602 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002603
2604 p = f;
2605 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002606 zeropad = 0;
2607 if (*f == '0') {
2608 zeropad = 1;
2609 f++;
2610 }
Victor Stinner96865452011-03-01 23:44:09 +00002611
2612 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002613 width = -1;
2614 if (Py_ISDIGIT((unsigned)*f)) {
2615 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002616 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002617 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002618 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002619 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002620 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002621 return NULL;
2622 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002623 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002624 f++;
2625 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002626 }
2627 precision = -1;
2628 if (*f == '.') {
2629 f++;
2630 if (Py_ISDIGIT((unsigned)*f)) {
2631 precision = (*f - '0');
2632 f++;
2633 while (Py_ISDIGIT((unsigned)*f)) {
2634 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2635 PyErr_SetString(PyExc_ValueError,
2636 "precision too big");
2637 return NULL;
2638 }
2639 precision = (precision * 10) + (*f - '0');
2640 f++;
2641 }
2642 }
Victor Stinner96865452011-03-01 23:44:09 +00002643 if (*f == '%') {
2644 /* "%.3%s" => f points to "3" */
2645 f--;
2646 }
2647 }
2648 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002649 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002650 f--;
2651 }
Victor Stinner96865452011-03-01 23:44:09 +00002652
2653 /* Handle %ld, %lu, %lld and %llu. */
2654 longflag = 0;
2655 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002656 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002657 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002658 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002659 longflag = 1;
2660 ++f;
2661 }
Victor Stinner96865452011-03-01 23:44:09 +00002662 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002663 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002664 longlongflag = 1;
2665 f += 2;
2666 }
Victor Stinner96865452011-03-01 23:44:09 +00002667 }
2668 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002669 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002670 size_tflag = 1;
2671 ++f;
2672 }
Victor Stinnere215d962012-10-06 23:03:36 +02002673
2674 if (f[1] == '\0')
2675 writer->overallocate = 0;
2676
2677 switch (*f) {
2678 case 'c':
2679 {
2680 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002681 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002682 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002683 "character argument not in range(0x110000)");
2684 return NULL;
2685 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002686 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002687 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002688 break;
2689 }
2690
2691 case 'i':
2692 case 'd':
2693 case 'u':
2694 case 'x':
2695 {
2696 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002697 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002698 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002699
2700 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002701 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002702 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002703 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002704 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002705 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002706 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002707 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002708 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002709 va_arg(*vargs, size_t));
2710 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002711 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002712 va_arg(*vargs, unsigned int));
2713 }
2714 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002715 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002716 }
2717 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002718 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002719 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002720 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002721 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002722 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002723 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002724 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002725 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002726 va_arg(*vargs, Py_ssize_t));
2727 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002728 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002729 va_arg(*vargs, int));
2730 }
2731 assert(len >= 0);
2732
Victor Stinnere215d962012-10-06 23:03:36 +02002733 if (precision < len)
2734 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002735
2736 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002737 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2738 return NULL;
2739
Victor Stinnere215d962012-10-06 23:03:36 +02002740 if (width > precision) {
2741 Py_UCS4 fillchar;
2742 fill = width - precision;
2743 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002744 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2745 return NULL;
2746 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002747 }
Victor Stinner15a11362012-10-06 23:48:20 +02002748 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002749 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002750 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2751 return NULL;
2752 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002753 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002754
Victor Stinner4a587072013-11-19 12:54:53 +01002755 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2756 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002757 break;
2758 }
2759
2760 case 'p':
2761 {
2762 char number[MAX_LONG_LONG_CHARS];
2763
2764 len = sprintf(number, "%p", va_arg(*vargs, void*));
2765 assert(len >= 0);
2766
2767 /* %p is ill-defined: ensure leading 0x. */
2768 if (number[1] == 'X')
2769 number[1] = 'x';
2770 else if (number[1] != 'x') {
2771 memmove(number + 2, number,
2772 strlen(number) + 1);
2773 number[0] = '0';
2774 number[1] = 'x';
2775 len += 2;
2776 }
2777
Victor Stinner4a587072013-11-19 12:54:53 +01002778 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002779 return NULL;
2780 break;
2781 }
2782
2783 case 's':
2784 {
2785 /* UTF-8 */
2786 const char *s = va_arg(*vargs, const char*);
Victor Stinner998b8062018-09-12 00:23:25 +02002787 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002788 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002789 break;
2790 }
2791
2792 case 'U':
2793 {
2794 PyObject *obj = va_arg(*vargs, PyObject *);
2795 assert(obj && _PyUnicode_CHECK(obj));
2796
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002797 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002798 return NULL;
2799 break;
2800 }
2801
2802 case 'V':
2803 {
2804 PyObject *obj = va_arg(*vargs, PyObject *);
2805 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002806 if (obj) {
2807 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002808 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002809 return NULL;
2810 }
2811 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002812 assert(str != NULL);
Victor Stinner998b8062018-09-12 00:23:25 +02002813 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002814 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002815 }
2816 break;
2817 }
2818
2819 case 'S':
2820 {
2821 PyObject *obj = va_arg(*vargs, PyObject *);
2822 PyObject *str;
2823 assert(obj);
2824 str = PyObject_Str(obj);
2825 if (!str)
2826 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002827 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002828 Py_DECREF(str);
2829 return NULL;
2830 }
2831 Py_DECREF(str);
2832 break;
2833 }
2834
2835 case 'R':
2836 {
2837 PyObject *obj = va_arg(*vargs, PyObject *);
2838 PyObject *repr;
2839 assert(obj);
2840 repr = PyObject_Repr(obj);
2841 if (!repr)
2842 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002843 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002844 Py_DECREF(repr);
2845 return NULL;
2846 }
2847 Py_DECREF(repr);
2848 break;
2849 }
2850
2851 case 'A':
2852 {
2853 PyObject *obj = va_arg(*vargs, PyObject *);
2854 PyObject *ascii;
2855 assert(obj);
2856 ascii = PyObject_ASCII(obj);
2857 if (!ascii)
2858 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002859 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002860 Py_DECREF(ascii);
2861 return NULL;
2862 }
2863 Py_DECREF(ascii);
2864 break;
2865 }
2866
2867 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002868 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002869 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002870 break;
2871
2872 default:
2873 /* if we stumble upon an unknown formatting code, copy the rest
2874 of the format string to the output string. (we cannot just
2875 skip the code, since there's no way to know what's in the
2876 argument list) */
2877 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002878 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002879 return NULL;
2880 f = p+len;
2881 return f;
2882 }
2883
2884 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002885 return f;
2886}
2887
Walter Dörwaldd2034312007-05-18 16:29:38 +00002888PyObject *
2889PyUnicode_FromFormatV(const char *format, va_list vargs)
2890{
Victor Stinnere215d962012-10-06 23:03:36 +02002891 va_list vargs2;
2892 const char *f;
2893 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002894
Victor Stinner8f674cc2013-04-17 23:02:17 +02002895 _PyUnicodeWriter_Init(&writer);
2896 writer.min_length = strlen(format) + 100;
2897 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002898
Benjamin Peterson0c212142016-09-20 20:39:33 -07002899 // Copy varags to be able to pass a reference to a subfunction.
2900 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002901
2902 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002903 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002904 f = unicode_fromformat_arg(&writer, f, &vargs2);
2905 if (f == NULL)
2906 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002907 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002908 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002909 const char *p;
2910 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002911
Victor Stinnere215d962012-10-06 23:03:36 +02002912 p = f;
2913 do
2914 {
2915 if ((unsigned char)*p > 127) {
2916 PyErr_Format(PyExc_ValueError,
2917 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2918 "string, got a non-ASCII byte: 0x%02x",
2919 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002920 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002921 }
2922 p++;
2923 }
2924 while (*p != '\0' && *p != '%');
2925 len = p - f;
2926
2927 if (*p == '\0')
2928 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002929
2930 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002931 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002932
2933 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002934 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002935 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002936 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002937 return _PyUnicodeWriter_Finish(&writer);
2938
2939 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002940 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002941 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002942 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002943}
2944
Walter Dörwaldd2034312007-05-18 16:29:38 +00002945PyObject *
2946PyUnicode_FromFormat(const char *format, ...)
2947{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002948 PyObject* ret;
2949 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002950
2951#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002952 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002953#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002954 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002955#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002956 ret = PyUnicode_FromFormatV(format, vargs);
2957 va_end(vargs);
2958 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002959}
2960
Serhiy Storchakac46db922018-10-23 22:58:24 +03002961static Py_ssize_t
2962unicode_get_widechar_size(PyObject *unicode)
2963{
2964 Py_ssize_t res;
2965
2966 assert(unicode != NULL);
2967 assert(_PyUnicode_CHECK(unicode));
2968
2969 if (_PyUnicode_WSTR(unicode) != NULL) {
2970 return PyUnicode_WSTR_LENGTH(unicode);
2971 }
2972 assert(PyUnicode_IS_READY(unicode));
2973
2974 res = _PyUnicode_LENGTH(unicode);
2975#if SIZEOF_WCHAR_T == 2
2976 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
2977 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
2978 const Py_UCS4 *end = s + res;
2979 for (; s < end; ++s) {
2980 if (*s > 0xFFFF) {
2981 ++res;
2982 }
2983 }
2984 }
2985#endif
2986 return res;
2987}
2988
2989static void
2990unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
2991{
2992 const wchar_t *wstr;
2993
2994 assert(unicode != NULL);
2995 assert(_PyUnicode_CHECK(unicode));
2996
2997 wstr = _PyUnicode_WSTR(unicode);
2998 if (wstr != NULL) {
2999 memcpy(w, wstr, size * sizeof(wchar_t));
3000 return;
3001 }
3002 assert(PyUnicode_IS_READY(unicode));
3003
3004 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3005 const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3006 for (; size--; ++s, ++w) {
3007 *w = *s;
3008 }
3009 }
3010 else {
3011#if SIZEOF_WCHAR_T == 4
3012 assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3013 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3014 for (; size--; ++s, ++w) {
3015 *w = *s;
3016 }
3017#else
3018 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
3019 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3020 for (; size--; ++s, ++w) {
3021 Py_UCS4 ch = *s;
3022 if (ch > 0xFFFF) {
3023 assert(ch <= MAX_UNICODE);
3024 /* encode surrogate pair in this case */
3025 *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
3026 if (!size--)
3027 break;
3028 *w = Py_UNICODE_LOW_SURROGATE(ch);
3029 }
3030 else {
3031 *w = ch;
3032 }
3033 }
3034#endif
3035 }
3036}
3037
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003038#ifdef HAVE_WCHAR_H
3039
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003040/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00003041
Victor Stinnerd88d9832011-09-06 02:00:05 +02003042 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003043 character) required to convert the unicode object. Ignore size argument.
3044
Victor Stinnerd88d9832011-09-06 02:00:05 +02003045 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003046 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02003047 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003048Py_ssize_t
3049PyUnicode_AsWideChar(PyObject *unicode,
3050 wchar_t *w,
3051 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00003052{
Victor Stinner5593d8a2010-10-02 11:11:27 +00003053 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003054
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003055 if (unicode == NULL) {
3056 PyErr_BadInternalCall();
3057 return -1;
3058 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003059 if (!PyUnicode_Check(unicode)) {
3060 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003061 return -1;
Victor Stinner5593d8a2010-10-02 11:11:27 +00003062 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003063
3064 res = unicode_get_widechar_size(unicode);
3065 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003066 return res + 1;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003067 }
3068
3069 if (size > res) {
3070 size = res + 1;
3071 }
3072 else {
3073 res = size;
3074 }
3075 unicode_copy_as_widechar(unicode, w, size);
3076 return res;
Victor Stinner137c34c2010-09-29 10:25:54 +00003077}
3078
Victor Stinner137c34c2010-09-29 10:25:54 +00003079wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003080PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00003081 Py_ssize_t *size)
3082{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003083 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00003084 Py_ssize_t buflen;
3085
3086 if (unicode == NULL) {
3087 PyErr_BadInternalCall();
3088 return NULL;
3089 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003090 if (!PyUnicode_Check(unicode)) {
3091 PyErr_BadArgument();
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003092 return NULL;
3093 }
3094
Serhiy Storchakac46db922018-10-23 22:58:24 +03003095 buflen = unicode_get_widechar_size(unicode);
3096 buffer = (wchar_t *) PyMem_NEW(wchar_t, (buflen + 1));
Victor Stinner137c34c2010-09-29 10:25:54 +00003097 if (buffer == NULL) {
3098 PyErr_NoMemory();
3099 return NULL;
3100 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003101 unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3102 if (size != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00003103 *size = buflen;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003104 }
3105 else if (wcslen(buffer) != (size_t)buflen) {
3106 PyMem_FREE(buffer);
3107 PyErr_SetString(PyExc_ValueError,
3108 "embedded null character");
3109 return NULL;
3110 }
Victor Stinner137c34c2010-09-29 10:25:54 +00003111 return buffer;
3112}
3113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003114#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003115
Alexander Belopolsky40018472011-02-26 01:02:56 +00003116PyObject *
3117PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003118{
Victor Stinner8faf8212011-12-08 22:14:11 +01003119 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003120 PyErr_SetString(PyExc_ValueError,
3121 "chr() arg not in range(0x110000)");
3122 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003123 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003124
Victor Stinner985a82a2014-01-03 12:53:47 +01003125 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003126}
3127
Alexander Belopolsky40018472011-02-26 01:02:56 +00003128PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003129PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003130{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003131 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003132 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003133 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003134 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003135 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003136 Py_INCREF(obj);
3137 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003138 }
3139 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003140 /* For a Unicode subtype that's not a Unicode object,
3141 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003142 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003143 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003144 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003145 "Can't convert '%.100s' object to str implicitly",
3146 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003147 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003148}
3149
Alexander Belopolsky40018472011-02-26 01:02:56 +00003150PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003151PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003152 const char *encoding,
3153 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003154{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003155 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003156 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003157
Guido van Rossumd57fd912000-03-10 22:53:23 +00003158 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003159 PyErr_BadInternalCall();
3160 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003161 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003162
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003163 /* Decoding bytes objects is the most common case and should be fast */
3164 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003165 if (PyBytes_GET_SIZE(obj) == 0)
3166 _Py_RETURN_UNICODE_EMPTY();
3167 v = PyUnicode_Decode(
3168 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3169 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003170 return v;
3171 }
3172
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003173 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003174 PyErr_SetString(PyExc_TypeError,
3175 "decoding str is not supported");
3176 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003177 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003178
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003179 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3180 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3181 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003182 "decoding to str: need a bytes-like object, %.80s found",
3183 Py_TYPE(obj)->tp_name);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003184 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003185 }
Tim Petersced69f82003-09-16 20:30:58 +00003186
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003187 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003188 PyBuffer_Release(&buffer);
3189 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003190 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003191
Serhiy Storchaka05997252013-01-26 12:14:02 +02003192 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003193 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003194 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003195}
3196
Victor Stinnerebe17e02016-10-12 13:57:45 +02003197/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3198 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3199 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003200int
3201_Py_normalize_encoding(const char *encoding,
3202 char *lower,
3203 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003204{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003205 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003206 char *l;
3207 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003208 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003209
Victor Stinner942889a2016-09-05 15:40:10 -07003210 assert(encoding != NULL);
3211
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003212 e = encoding;
3213 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003214 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003215 punct = 0;
3216 while (1) {
3217 char c = *e;
3218 if (c == 0) {
3219 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003220 }
Victor Stinner942889a2016-09-05 15:40:10 -07003221
3222 if (Py_ISALNUM(c) || c == '.') {
3223 if (punct && l != lower) {
3224 if (l == l_end) {
3225 return 0;
3226 }
3227 *l++ = '_';
3228 }
3229 punct = 0;
3230
3231 if (l == l_end) {
3232 return 0;
3233 }
3234 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003235 }
3236 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003237 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003238 }
Victor Stinner942889a2016-09-05 15:40:10 -07003239
3240 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003241 }
3242 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003243 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003244}
3245
Alexander Belopolsky40018472011-02-26 01:02:56 +00003246PyObject *
3247PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003248 Py_ssize_t size,
3249 const char *encoding,
3250 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003251{
3252 PyObject *buffer = NULL, *unicode;
3253 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003254 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3255
3256 if (encoding == NULL) {
3257 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3258 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003259
Fred Drakee4315f52000-05-09 19:53:39 +00003260 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003261 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3262 char *lower = buflower;
3263
3264 /* Fast paths */
3265 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3266 lower += 3;
3267 if (*lower == '_') {
3268 /* Match "utf8" and "utf_8" */
3269 lower++;
3270 }
3271
3272 if (lower[0] == '8' && lower[1] == 0) {
3273 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3274 }
3275 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3276 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3277 }
3278 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3279 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3280 }
3281 }
3282 else {
3283 if (strcmp(lower, "ascii") == 0
3284 || strcmp(lower, "us_ascii") == 0) {
3285 return PyUnicode_DecodeASCII(s, size, errors);
3286 }
Steve Dowercc16be82016-09-08 10:35:16 -07003287 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003288 else if (strcmp(lower, "mbcs") == 0) {
3289 return PyUnicode_DecodeMBCS(s, size, errors);
3290 }
3291 #endif
3292 else if (strcmp(lower, "latin1") == 0
3293 || strcmp(lower, "latin_1") == 0
3294 || strcmp(lower, "iso_8859_1") == 0
3295 || strcmp(lower, "iso8859_1") == 0) {
3296 return PyUnicode_DecodeLatin1(s, size, errors);
3297 }
3298 }
Victor Stinner37296e82010-06-10 13:36:23 +00003299 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003300
3301 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003302 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003303 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003304 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003305 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003306 if (buffer == NULL)
3307 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003308 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003309 if (unicode == NULL)
3310 goto onError;
3311 if (!PyUnicode_Check(unicode)) {
3312 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003313 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003314 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003315 encoding,
3316 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003317 Py_DECREF(unicode);
3318 goto onError;
3319 }
3320 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003321 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003322
Benjamin Peterson29060642009-01-31 22:14:21 +00003323 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003324 Py_XDECREF(buffer);
3325 return NULL;
3326}
3327
Alexander Belopolsky40018472011-02-26 01:02:56 +00003328PyObject *
3329PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003330 const char *encoding,
3331 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003332{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003333 if (!PyUnicode_Check(unicode)) {
3334 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003335 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003336 }
3337
Serhiy Storchaka00939072016-10-27 21:05:49 +03003338 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3339 "PyUnicode_AsDecodedObject() is deprecated; "
3340 "use PyCodec_Decode() to decode from str", 1) < 0)
3341 return NULL;
3342
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003343 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003344 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003345
3346 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003347 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003348}
3349
Alexander Belopolsky40018472011-02-26 01:02:56 +00003350PyObject *
3351PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003352 const char *encoding,
3353 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003354{
3355 PyObject *v;
3356
3357 if (!PyUnicode_Check(unicode)) {
3358 PyErr_BadArgument();
3359 goto onError;
3360 }
3361
Serhiy Storchaka00939072016-10-27 21:05:49 +03003362 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3363 "PyUnicode_AsDecodedUnicode() is deprecated; "
3364 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3365 return NULL;
3366
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003367 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003368 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003369
3370 /* Decode via the codec registry */
3371 v = PyCodec_Decode(unicode, encoding, errors);
3372 if (v == NULL)
3373 goto onError;
3374 if (!PyUnicode_Check(v)) {
3375 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003376 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003377 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003378 encoding,
3379 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003380 Py_DECREF(v);
3381 goto onError;
3382 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003383 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003384
Benjamin Peterson29060642009-01-31 22:14:21 +00003385 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003386 return NULL;
3387}
3388
Alexander Belopolsky40018472011-02-26 01:02:56 +00003389PyObject *
3390PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003391 Py_ssize_t size,
3392 const char *encoding,
3393 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003394{
3395 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003396
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003397 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003398 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003399 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003400 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3401 Py_DECREF(unicode);
3402 return v;
3403}
3404
Alexander Belopolsky40018472011-02-26 01:02:56 +00003405PyObject *
3406PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003407 const char *encoding,
3408 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003409{
3410 PyObject *v;
3411
3412 if (!PyUnicode_Check(unicode)) {
3413 PyErr_BadArgument();
3414 goto onError;
3415 }
3416
Serhiy Storchaka00939072016-10-27 21:05:49 +03003417 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3418 "PyUnicode_AsEncodedObject() is deprecated; "
3419 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3420 "or PyCodec_Encode() for generic encoding", 1) < 0)
3421 return NULL;
3422
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003423 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003424 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003425
3426 /* Encode via the codec registry */
3427 v = PyCodec_Encode(unicode, encoding, errors);
3428 if (v == NULL)
3429 goto onError;
3430 return v;
3431
Benjamin Peterson29060642009-01-31 22:14:21 +00003432 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003433 return NULL;
3434}
3435
Victor Stinner1b579672011-12-17 05:47:23 +01003436
Victor Stinner2cba6b82018-01-10 22:46:15 +01003437static PyObject *
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003438unicode_encode_locale(PyObject *unicode, const char *errors,
3439 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003440{
Victor Stinner3d4226a2018-08-29 22:21:32 +02003441 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003442
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003443 Py_ssize_t wlen;
3444 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3445 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003446 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003447 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003448
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003449 Py_ssize_t wlen2 = wcslen(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003450 if (wlen2 != wlen) {
3451 PyMem_Free(wstr);
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003452 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003453 return NULL;
3454 }
3455
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003456 char *str;
3457 size_t error_pos;
3458 const char *reason;
3459 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003460 current_locale, error_handler);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003461 if (res != 0) {
3462 if (res == -2) {
3463 PyObject *exc;
3464 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3465 "locale", unicode,
3466 (Py_ssize_t)error_pos,
3467 (Py_ssize_t)(error_pos+1),
3468 reason);
3469 if (exc != NULL) {
3470 PyCodec_StrictErrors(exc);
3471 Py_DECREF(exc);
3472 }
3473 return NULL;
Victor Stinner2cba6b82018-01-10 22:46:15 +01003474 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003475 else if (res == -3) {
3476 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3477 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003478 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003479 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003480 PyMem_Free(wstr);
3481 return NULL;
3482 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003483 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003484 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003485
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003486 PyObject *bytes = PyBytes_FromString(str);
3487 PyMem_RawFree(str);
3488 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003489}
3490
Victor Stinnerad158722010-10-27 00:25:46 +00003491PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003492PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3493{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003494 return unicode_encode_locale(unicode, errors, 1);
3495}
3496
3497PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003498PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003499{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003500 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003501 const _PyCoreConfig *config = &interp->core_config;
3502#if defined(__APPLE__)
3503 return _PyUnicode_AsUTF8String(unicode, config->filesystem_errors);
3504#else
Victor Stinner793b5312011-04-27 00:24:21 +02003505 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3506 cannot use it to encode and decode filenames before it is loaded. Load
3507 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003508 implementation of the locale codec until the codec registry is
3509 initialized and the Python codec is loaded. See initfsencoding(). */
3510 if (interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003511 return PyUnicode_AsEncodedString(unicode,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003512 config->filesystem_encoding,
3513 config->filesystem_errors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003514 }
3515 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003516 return unicode_encode_locale(unicode,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003517 config->filesystem_errors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003518 }
Victor Stinnerad158722010-10-27 00:25:46 +00003519#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003520}
3521
Alexander Belopolsky40018472011-02-26 01:02:56 +00003522PyObject *
3523PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003524 const char *encoding,
3525 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003526{
3527 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003528 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003529
Guido van Rossumd57fd912000-03-10 22:53:23 +00003530 if (!PyUnicode_Check(unicode)) {
3531 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003532 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003533 }
Fred Drakee4315f52000-05-09 19:53:39 +00003534
Victor Stinner942889a2016-09-05 15:40:10 -07003535 if (encoding == NULL) {
3536 return _PyUnicode_AsUTF8String(unicode, errors);
3537 }
3538
Fred Drakee4315f52000-05-09 19:53:39 +00003539 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003540 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3541 char *lower = buflower;
3542
3543 /* Fast paths */
3544 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3545 lower += 3;
3546 if (*lower == '_') {
3547 /* Match "utf8" and "utf_8" */
3548 lower++;
3549 }
3550
3551 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003552 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003553 }
3554 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3555 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3556 }
3557 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3558 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3559 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003560 }
Victor Stinner942889a2016-09-05 15:40:10 -07003561 else {
3562 if (strcmp(lower, "ascii") == 0
3563 || strcmp(lower, "us_ascii") == 0) {
3564 return _PyUnicode_AsASCIIString(unicode, errors);
3565 }
Steve Dowercc16be82016-09-08 10:35:16 -07003566#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003567 else if (strcmp(lower, "mbcs") == 0) {
3568 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3569 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003570#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003571 else if (strcmp(lower, "latin1") == 0 ||
3572 strcmp(lower, "latin_1") == 0 ||
3573 strcmp(lower, "iso_8859_1") == 0 ||
3574 strcmp(lower, "iso8859_1") == 0) {
3575 return _PyUnicode_AsLatin1String(unicode, errors);
3576 }
3577 }
Victor Stinner37296e82010-06-10 13:36:23 +00003578 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003579
3580 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003581 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003582 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003583 return NULL;
3584
3585 /* The normal path */
3586 if (PyBytes_Check(v))
3587 return v;
3588
3589 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003590 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003591 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003592 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003593
3594 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003595 "encoder %s returned bytearray instead of bytes; "
3596 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003597 encoding);
3598 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003599 Py_DECREF(v);
3600 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003601 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003602
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003603 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3604 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003605 Py_DECREF(v);
3606 return b;
3607 }
3608
3609 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003610 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003611 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003612 encoding,
3613 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003614 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003615 return NULL;
3616}
3617
Alexander Belopolsky40018472011-02-26 01:02:56 +00003618PyObject *
3619PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003620 const char *encoding,
3621 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003622{
3623 PyObject *v;
3624
3625 if (!PyUnicode_Check(unicode)) {
3626 PyErr_BadArgument();
3627 goto onError;
3628 }
3629
Serhiy Storchaka00939072016-10-27 21:05:49 +03003630 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3631 "PyUnicode_AsEncodedUnicode() is deprecated; "
3632 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3633 return NULL;
3634
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003635 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003636 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003637
3638 /* Encode via the codec registry */
3639 v = PyCodec_Encode(unicode, encoding, errors);
3640 if (v == NULL)
3641 goto onError;
3642 if (!PyUnicode_Check(v)) {
3643 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003644 "'%.400s' encoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003645 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003646 encoding,
3647 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003648 Py_DECREF(v);
3649 goto onError;
3650 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003651 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003652
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003654 return NULL;
3655}
3656
Victor Stinner2cba6b82018-01-10 22:46:15 +01003657static PyObject*
3658unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3659 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003660{
Victor Stinner3d4226a2018-08-29 22:21:32 +02003661 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003662
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003663 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3664 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003665 return NULL;
3666 }
3667
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003668 wchar_t *wstr;
3669 size_t wlen;
3670 const char *reason;
3671 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003672 current_locale, error_handler);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003673 if (res != 0) {
3674 if (res == -2) {
3675 PyObject *exc;
3676 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3677 "locale", str, len,
3678 (Py_ssize_t)wlen,
3679 (Py_ssize_t)(wlen + 1),
3680 reason);
3681 if (exc != NULL) {
3682 PyCodec_StrictErrors(exc);
3683 Py_DECREF(exc);
3684 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003685 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003686 else if (res == -3) {
3687 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3688 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003689 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003690 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003691 }
Victor Stinner2f197072011-12-17 07:08:30 +01003692 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003693 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003694
3695 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3696 PyMem_RawFree(wstr);
3697 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003698}
3699
3700PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003701PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3702 const char *errors)
3703{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003704 return unicode_decode_locale(str, len, errors, 1);
3705}
3706
3707PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003708PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003709{
3710 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003711 return unicode_decode_locale(str, size, errors, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003712}
3713
3714
3715PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003716PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003717 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003718 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3719}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003720
Christian Heimes5894ba72007-11-04 11:43:14 +00003721PyObject*
3722PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3723{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003724 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003725 const _PyCoreConfig *config = &interp->core_config;
3726#if defined(__APPLE__)
3727 return PyUnicode_DecodeUTF8Stateful(s, size, config->filesystem_errors, NULL);
3728#else
Victor Stinner793b5312011-04-27 00:24:21 +02003729 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3730 cannot use it to encode and decode filenames before it is loaded. Load
3731 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003732 implementation of the locale codec until the codec registry is
3733 initialized and the Python codec is loaded. See initfsencoding(). */
3734 if (interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003735 return PyUnicode_Decode(s, size,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003736 config->filesystem_encoding,
3737 config->filesystem_errors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003738 }
3739 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003740 return unicode_decode_locale(s, size,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003741 config->filesystem_errors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003742 }
Victor Stinnerad158722010-10-27 00:25:46 +00003743#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003744}
3745
Martin v. Löwis011e8422009-05-05 04:43:17 +00003746
3747int
3748PyUnicode_FSConverter(PyObject* arg, void* addr)
3749{
Brett Cannonec6ce872016-09-06 15:50:29 -07003750 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003751 PyObject *output = NULL;
3752 Py_ssize_t size;
3753 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003754 if (arg == NULL) {
3755 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003756 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003757 return 1;
3758 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003759 path = PyOS_FSPath(arg);
3760 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003761 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003762 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003763 if (PyBytes_Check(path)) {
3764 output = path;
3765 }
3766 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3767 output = PyUnicode_EncodeFSDefault(path);
3768 Py_DECREF(path);
3769 if (!output) {
3770 return 0;
3771 }
3772 assert(PyBytes_Check(output));
3773 }
3774
Victor Stinner0ea2a462010-04-30 00:22:08 +00003775 size = PyBytes_GET_SIZE(output);
3776 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003777 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003778 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003779 Py_DECREF(output);
3780 return 0;
3781 }
3782 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003783 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003784}
3785
3786
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003787int
3788PyUnicode_FSDecoder(PyObject* arg, void* addr)
3789{
Brett Cannona5711202016-09-06 19:36:01 -07003790 int is_buffer = 0;
3791 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003792 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003793 if (arg == NULL) {
3794 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003795 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003796 return 1;
3797 }
Brett Cannona5711202016-09-06 19:36:01 -07003798
3799 is_buffer = PyObject_CheckBuffer(arg);
3800 if (!is_buffer) {
3801 path = PyOS_FSPath(arg);
3802 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003803 return 0;
3804 }
Brett Cannona5711202016-09-06 19:36:01 -07003805 }
3806 else {
3807 path = arg;
3808 Py_INCREF(arg);
3809 }
3810
3811 if (PyUnicode_Check(path)) {
Brett Cannona5711202016-09-06 19:36:01 -07003812 output = path;
3813 }
3814 else if (PyBytes_Check(path) || is_buffer) {
3815 PyObject *path_bytes = NULL;
3816
3817 if (!PyBytes_Check(path) &&
3818 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Victor Stinner998b8062018-09-12 00:23:25 +02003819 "path should be string, bytes, or os.PathLike, not %.200s",
3820 Py_TYPE(arg)->tp_name)) {
3821 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003822 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003823 }
3824 path_bytes = PyBytes_FromObject(path);
3825 Py_DECREF(path);
3826 if (!path_bytes) {
3827 return 0;
3828 }
3829 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3830 PyBytes_GET_SIZE(path_bytes));
3831 Py_DECREF(path_bytes);
3832 if (!output) {
3833 return 0;
3834 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003835 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003836 else {
3837 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003838 "path should be string, bytes, or os.PathLike, not %.200s",
3839 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003840 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003841 return 0;
3842 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003843 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003844 Py_DECREF(output);
3845 return 0;
3846 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003847 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003848 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003849 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003850 Py_DECREF(output);
3851 return 0;
3852 }
3853 *(PyObject**)addr = output;
3854 return Py_CLEANUP_SUPPORTED;
3855}
3856
3857
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003858const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003859PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003860{
Christian Heimesf3863112007-11-22 07:46:41 +00003861 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003862
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003863 if (!PyUnicode_Check(unicode)) {
3864 PyErr_BadArgument();
3865 return NULL;
3866 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003867 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003868 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003869
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003870 if (PyUnicode_UTF8(unicode) == NULL) {
3871 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003872 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003873 if (bytes == NULL)
3874 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003875 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3876 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003877 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003878 Py_DECREF(bytes);
3879 return NULL;
3880 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003881 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003882 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003883 PyBytes_AS_STRING(bytes),
3884 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003885 Py_DECREF(bytes);
3886 }
3887
3888 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003889 *psize = PyUnicode_UTF8_LENGTH(unicode);
3890 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003891}
3892
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003893const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003894PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003895{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003896 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3897}
3898
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003899Py_UNICODE *
3900PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3901{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003902 if (!PyUnicode_Check(unicode)) {
3903 PyErr_BadArgument();
3904 return NULL;
3905 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003906 Py_UNICODE *w = _PyUnicode_WSTR(unicode);
3907 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003908 /* Non-ASCII compact unicode object */
Serhiy Storchakac46db922018-10-23 22:58:24 +03003909 assert(_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003910 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003911
Serhiy Storchakac46db922018-10-23 22:58:24 +03003912 Py_ssize_t wlen = unicode_get_widechar_size(unicode);
3913 if ((size_t)wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3914 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003915 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003916 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003917 w = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) * (wlen + 1));
3918 if (w == NULL) {
3919 PyErr_NoMemory();
3920 return NULL;
3921 }
3922 unicode_copy_as_widechar(unicode, w, wlen + 1);
3923 _PyUnicode_WSTR(unicode) = w;
3924 if (!PyUnicode_IS_COMPACT_ASCII(unicode)) {
3925 _PyUnicode_WSTR_LENGTH(unicode) = wlen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003926 }
3927 }
3928 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003929 *size = PyUnicode_WSTR_LENGTH(unicode);
Serhiy Storchakac46db922018-10-23 22:58:24 +03003930 return w;
Martin v. Löwis5b222132007-06-10 09:51:05 +00003931}
3932
Alexander Belopolsky40018472011-02-26 01:02:56 +00003933Py_UNICODE *
3934PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003935{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003936 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003937}
3938
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03003939const Py_UNICODE *
3940_PyUnicode_AsUnicode(PyObject *unicode)
3941{
3942 Py_ssize_t size;
3943 const Py_UNICODE *wstr;
3944
3945 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
3946 if (wstr && wcslen(wstr) != (size_t)size) {
3947 PyErr_SetString(PyExc_ValueError, "embedded null character");
3948 return NULL;
3949 }
3950 return wstr;
3951}
3952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003953
Alexander Belopolsky40018472011-02-26 01:02:56 +00003954Py_ssize_t
3955PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003956{
3957 if (!PyUnicode_Check(unicode)) {
3958 PyErr_BadArgument();
3959 goto onError;
3960 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003961 if (_PyUnicode_WSTR(unicode) == NULL) {
3962 if (PyUnicode_AsUnicode(unicode) == NULL)
3963 goto onError;
3964 }
3965 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003966
Benjamin Peterson29060642009-01-31 22:14:21 +00003967 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003968 return -1;
3969}
3970
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003971Py_ssize_t
3972PyUnicode_GetLength(PyObject *unicode)
3973{
Victor Stinner07621332012-06-16 04:53:46 +02003974 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003975 PyErr_BadArgument();
3976 return -1;
3977 }
Victor Stinner07621332012-06-16 04:53:46 +02003978 if (PyUnicode_READY(unicode) == -1)
3979 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003980 return PyUnicode_GET_LENGTH(unicode);
3981}
3982
3983Py_UCS4
3984PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3985{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003986 void *data;
3987 int kind;
3988
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003989 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003990 PyErr_BadArgument();
3991 return (Py_UCS4)-1;
3992 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003993 if (PyUnicode_READY(unicode) == -1) {
3994 return (Py_UCS4)-1;
3995 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003996 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003997 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003998 return (Py_UCS4)-1;
3999 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004000 data = PyUnicode_DATA(unicode);
4001 kind = PyUnicode_KIND(unicode);
4002 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004003}
4004
4005int
4006PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4007{
4008 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004009 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004010 return -1;
4011 }
Victor Stinner488fa492011-12-12 00:01:39 +01004012 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004013 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004014 PyErr_SetString(PyExc_IndexError, "string index out of range");
4015 return -1;
4016 }
Victor Stinner488fa492011-12-12 00:01:39 +01004017 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004018 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004019 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4020 PyErr_SetString(PyExc_ValueError, "character out of range");
4021 return -1;
4022 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004023 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4024 index, ch);
4025 return 0;
4026}
4027
Alexander Belopolsky40018472011-02-26 01:02:56 +00004028const char *
4029PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004030{
Victor Stinner42cb4622010-09-01 19:39:01 +00004031 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004032}
4033
Victor Stinner554f3f02010-06-16 23:33:54 +00004034/* create or adjust a UnicodeDecodeError */
4035static void
4036make_decode_exception(PyObject **exceptionObject,
4037 const char *encoding,
4038 const char *input, Py_ssize_t length,
4039 Py_ssize_t startpos, Py_ssize_t endpos,
4040 const char *reason)
4041{
4042 if (*exceptionObject == NULL) {
4043 *exceptionObject = PyUnicodeDecodeError_Create(
4044 encoding, input, length, startpos, endpos, reason);
4045 }
4046 else {
4047 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4048 goto onError;
4049 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4050 goto onError;
4051 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4052 goto onError;
4053 }
4054 return;
4055
4056onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004057 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004058}
4059
Steve Dowercc16be82016-09-08 10:35:16 -07004060#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004061/* error handling callback helper:
4062 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004063 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004064 and adjust various state variables.
4065 return 0 on success, -1 on error
4066*/
4067
Alexander Belopolsky40018472011-02-26 01:02:56 +00004068static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004069unicode_decode_call_errorhandler_wchar(
4070 const char *errors, PyObject **errorHandler,
4071 const char *encoding, const char *reason,
4072 const char **input, const char **inend, Py_ssize_t *startinpos,
4073 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4074 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004075{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004076 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004077
4078 PyObject *restuple = NULL;
4079 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004080 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004081 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004082 Py_ssize_t requiredsize;
4083 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004084 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004085 wchar_t *repwstr;
4086 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004087
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004088 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4089 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004090
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004091 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004092 *errorHandler = PyCodec_LookupError(errors);
4093 if (*errorHandler == NULL)
4094 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004095 }
4096
Victor Stinner554f3f02010-06-16 23:33:54 +00004097 make_decode_exception(exceptionObject,
4098 encoding,
4099 *input, *inend - *input,
4100 *startinpos, *endinpos,
4101 reason);
4102 if (*exceptionObject == NULL)
4103 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004104
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004105 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004106 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004107 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004108 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004109 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004110 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004111 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004112 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004113 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004114
4115 /* Copy back the bytes variables, which might have been modified by the
4116 callback */
4117 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4118 if (!inputobj)
4119 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004120 *input = PyBytes_AS_STRING(inputobj);
4121 insize = PyBytes_GET_SIZE(inputobj);
4122 *inend = *input + insize;
4123 /* we can DECREF safely, as the exception has another reference,
4124 so the object won't go away. */
4125 Py_DECREF(inputobj);
4126
4127 if (newpos<0)
4128 newpos = insize+newpos;
4129 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004130 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004131 goto onError;
4132 }
4133
4134 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4135 if (repwstr == NULL)
4136 goto onError;
4137 /* need more space? (at least enough for what we
4138 have+the replacement+the rest of the string (starting
4139 at the new input position), so we won't have to check space
4140 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004141 requiredsize = *outpos;
4142 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4143 goto overflow;
4144 requiredsize += repwlen;
4145 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4146 goto overflow;
4147 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004148 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004149 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004150 requiredsize = 2*outsize;
4151 if (unicode_resize(output, requiredsize) < 0)
4152 goto onError;
4153 }
4154 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4155 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004156 *endinpos = newpos;
4157 *inptr = *input + newpos;
4158
4159 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004160 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004161 return 0;
4162
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004163 overflow:
4164 PyErr_SetString(PyExc_OverflowError,
4165 "decoded result is too long for a Python string");
4166
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004167 onError:
4168 Py_XDECREF(restuple);
4169 return -1;
4170}
Steve Dowercc16be82016-09-08 10:35:16 -07004171#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004172
4173static int
4174unicode_decode_call_errorhandler_writer(
4175 const char *errors, PyObject **errorHandler,
4176 const char *encoding, const char *reason,
4177 const char **input, const char **inend, Py_ssize_t *startinpos,
4178 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4179 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4180{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004181 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004182
4183 PyObject *restuple = NULL;
4184 PyObject *repunicode = NULL;
4185 Py_ssize_t insize;
4186 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004187 Py_ssize_t replen;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004188 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004189 PyObject *inputobj = NULL;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004190 int need_to_grow = 0;
4191 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004192
4193 if (*errorHandler == NULL) {
4194 *errorHandler = PyCodec_LookupError(errors);
4195 if (*errorHandler == NULL)
4196 goto onError;
4197 }
4198
4199 make_decode_exception(exceptionObject,
4200 encoding,
4201 *input, *inend - *input,
4202 *startinpos, *endinpos,
4203 reason);
4204 if (*exceptionObject == NULL)
4205 goto onError;
4206
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004207 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004208 if (restuple == NULL)
4209 goto onError;
4210 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004211 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004212 goto onError;
4213 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004214 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004215 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004216
4217 /* Copy back the bytes variables, which might have been modified by the
4218 callback */
4219 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4220 if (!inputobj)
4221 goto onError;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004222 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004223 *input = PyBytes_AS_STRING(inputobj);
4224 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004225 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004226 /* we can DECREF safely, as the exception has another reference,
4227 so the object won't go away. */
4228 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004229
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004230 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004231 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004232 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004233 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004234 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004235 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004236
Victor Stinner170ca6f2013-04-18 00:25:28 +02004237 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004238 if (replen > 1) {
4239 writer->min_length += replen - 1;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004240 need_to_grow = 1;
4241 }
4242 new_inptr = *input + newpos;
4243 if (*inend - new_inptr > remain) {
4244 /* We don't know the decoding algorithm here so we make the worst
4245 assumption that one byte decodes to one unicode character.
4246 If unfortunately one byte could decode to more unicode characters,
4247 the decoder may write out-of-bound then. Is it possible for the
4248 algorithms using this function? */
4249 writer->min_length += *inend - new_inptr - remain;
4250 need_to_grow = 1;
4251 }
4252 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004253 writer->overallocate = 1;
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02004254 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004255 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4256 goto onError;
4257 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004258 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004259 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004260
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004261 *endinpos = newpos;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004262 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004263
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004264 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004265 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004266 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004267
Benjamin Peterson29060642009-01-31 22:14:21 +00004268 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004269 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004270 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004271}
4272
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004273/* --- UTF-7 Codec -------------------------------------------------------- */
4274
Antoine Pitrou244651a2009-05-04 18:56:13 +00004275/* See RFC2152 for details. We encode conservatively and decode liberally. */
4276
4277/* Three simple macros defining base-64. */
4278
4279/* Is c a base-64 character? */
4280
4281#define IS_BASE64(c) \
4282 (((c) >= 'A' && (c) <= 'Z') || \
4283 ((c) >= 'a' && (c) <= 'z') || \
4284 ((c) >= '0' && (c) <= '9') || \
4285 (c) == '+' || (c) == '/')
4286
4287/* given that c is a base-64 character, what is its base-64 value? */
4288
4289#define FROM_BASE64(c) \
4290 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4291 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4292 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4293 (c) == '+' ? 62 : 63)
4294
4295/* What is the base-64 character of the bottom 6 bits of n? */
4296
4297#define TO_BASE64(n) \
4298 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4299
4300/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4301 * decoded as itself. We are permissive on decoding; the only ASCII
4302 * byte not decoding to itself is the + which begins a base64
4303 * string. */
4304
4305#define DECODE_DIRECT(c) \
4306 ((c) <= 127 && (c) != '+')
4307
4308/* The UTF-7 encoder treats ASCII characters differently according to
4309 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4310 * the above). See RFC2152. This array identifies these different
4311 * sets:
4312 * 0 : "Set D"
4313 * alphanumeric and '(),-./:?
4314 * 1 : "Set O"
4315 * !"#$%&*;<=>@[]^_`{|}
4316 * 2 : "whitespace"
4317 * ht nl cr sp
4318 * 3 : special (must be base64 encoded)
4319 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4320 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004321
Tim Petersced69f82003-09-16 20:30:58 +00004322static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004323char utf7_category[128] = {
4324/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4325 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4326/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4327 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4328/* sp ! " # $ % & ' ( ) * + , - . / */
4329 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4330/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4331 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4332/* @ A B C D E F G H I J K L M N O */
4333 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4334/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4335 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4336/* ` a b c d e f g h i j k l m n o */
4337 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4338/* p q r s t u v w x y z { | } ~ del */
4339 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004340};
4341
Antoine Pitrou244651a2009-05-04 18:56:13 +00004342/* ENCODE_DIRECT: this character should be encoded as itself. The
4343 * answer depends on whether we are encoding set O as itself, and also
4344 * on whether we are encoding whitespace as itself. RFC2152 makes it
4345 * clear that the answers to these questions vary between
4346 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004347
Antoine Pitrou244651a2009-05-04 18:56:13 +00004348#define ENCODE_DIRECT(c, directO, directWS) \
4349 ((c) < 128 && (c) > 0 && \
4350 ((utf7_category[(c)] == 0) || \
4351 (directWS && (utf7_category[(c)] == 2)) || \
4352 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004353
Alexander Belopolsky40018472011-02-26 01:02:56 +00004354PyObject *
4355PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004356 Py_ssize_t size,
4357 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004358{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004359 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4360}
4361
Antoine Pitrou244651a2009-05-04 18:56:13 +00004362/* The decoder. The only state we preserve is our read position,
4363 * i.e. how many characters we have consumed. So if we end in the
4364 * middle of a shift sequence we have to back off the read position
4365 * and the output to the beginning of the sequence, otherwise we lose
4366 * all the shift state (seen bits, number of bits seen, high
4367 * surrogate). */
4368
Alexander Belopolsky40018472011-02-26 01:02:56 +00004369PyObject *
4370PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004371 Py_ssize_t size,
4372 const char *errors,
4373 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004374{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004375 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004376 Py_ssize_t startinpos;
4377 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004378 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004379 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004380 const char *errmsg = "";
4381 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004382 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004383 unsigned int base64bits = 0;
4384 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004385 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004386 PyObject *errorHandler = NULL;
4387 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004388
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004389 if (size == 0) {
4390 if (consumed)
4391 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004392 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004393 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004394
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004395 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004396 _PyUnicodeWriter_Init(&writer);
4397 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004398
4399 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004400 e = s + size;
4401
4402 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004403 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004404 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004405 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004406
Antoine Pitrou244651a2009-05-04 18:56:13 +00004407 if (inShift) { /* in a base-64 section */
4408 if (IS_BASE64(ch)) { /* consume a base-64 character */
4409 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4410 base64bits += 6;
4411 s++;
4412 if (base64bits >= 16) {
4413 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004414 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004415 base64bits -= 16;
4416 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004417 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004418 if (surrogate) {
4419 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004420 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4421 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004422 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004423 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004424 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004425 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004426 }
4427 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004428 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004429 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004430 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 }
4432 }
Victor Stinner551ac952011-11-29 22:58:13 +01004433 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004434 /* first surrogate */
4435 surrogate = outCh;
4436 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004437 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004438 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004439 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004440 }
4441 }
4442 }
4443 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004444 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004445 if (base64bits > 0) { /* left-over bits */
4446 if (base64bits >= 6) {
4447 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004448 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004449 errmsg = "partial character in shift sequence";
4450 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004451 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004452 else {
4453 /* Some bits remain; they should be zero */
4454 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004455 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004456 errmsg = "non-zero padding bits in shift sequence";
4457 goto utf7Error;
4458 }
4459 }
4460 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004461 if (surrogate && DECODE_DIRECT(ch)) {
4462 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4463 goto onError;
4464 }
4465 surrogate = 0;
4466 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004467 /* '-' is absorbed; other terminating
4468 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004469 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004470 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 }
4472 }
4473 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004474 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004475 s++; /* consume '+' */
4476 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004477 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004478 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004479 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004480 }
Zackery Spytze349bf22018-08-18 22:43:38 -06004481 else if (s < e && !IS_BASE64(*s)) {
4482 s++;
4483 errmsg = "ill-formed sequence";
4484 goto utf7Error;
4485 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004486 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004487 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004488 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004489 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004490 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004491 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004492 }
4493 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004494 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004495 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004496 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004497 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004498 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004499 else {
4500 startinpos = s-starts;
4501 s++;
4502 errmsg = "unexpected special character";
4503 goto utf7Error;
4504 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004505 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004506utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004507 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004508 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004509 errors, &errorHandler,
4510 "utf7", errmsg,
4511 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004512 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004513 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004514 }
4515
Antoine Pitrou244651a2009-05-04 18:56:13 +00004516 /* end of string */
4517
4518 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4519 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004520 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004521 if (surrogate ||
4522 (base64bits >= 6) ||
4523 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004524 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004525 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004526 errors, &errorHandler,
4527 "utf7", "unterminated shift sequence",
4528 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004529 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004530 goto onError;
4531 if (s < e)
4532 goto restart;
4533 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004534 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004535
4536 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004537 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004538 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004539 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004540 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004541 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004542 writer.kind, writer.data, shiftOutStart);
4543 Py_XDECREF(errorHandler);
4544 Py_XDECREF(exc);
4545 _PyUnicodeWriter_Dealloc(&writer);
4546 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004547 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004548 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004549 }
4550 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004551 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004552 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004553 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004554
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004555 Py_XDECREF(errorHandler);
4556 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004557 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004558
Benjamin Peterson29060642009-01-31 22:14:21 +00004559 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004560 Py_XDECREF(errorHandler);
4561 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004562 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004563 return NULL;
4564}
4565
4566
Alexander Belopolsky40018472011-02-26 01:02:56 +00004567PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004568_PyUnicode_EncodeUTF7(PyObject *str,
4569 int base64SetO,
4570 int base64WhiteSpace,
4571 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004572{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004573 int kind;
4574 void *data;
4575 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004576 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004577 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004578 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004579 unsigned int base64bits = 0;
4580 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004581 char * out;
4582 char * start;
4583
Benjamin Petersonbac79492012-01-14 13:34:47 -05004584 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004585 return NULL;
4586 kind = PyUnicode_KIND(str);
4587 data = PyUnicode_DATA(str);
4588 len = PyUnicode_GET_LENGTH(str);
4589
4590 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004591 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004592
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004593 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004594 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004595 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004596 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004597 if (v == NULL)
4598 return NULL;
4599
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004600 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004601 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004602 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004603
Antoine Pitrou244651a2009-05-04 18:56:13 +00004604 if (inShift) {
4605 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4606 /* shifting out */
4607 if (base64bits) { /* output remaining bits */
4608 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4609 base64buffer = 0;
4610 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004611 }
4612 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004613 /* Characters not in the BASE64 set implicitly unshift the sequence
4614 so no '-' is required, except if the character is itself a '-' */
4615 if (IS_BASE64(ch) || ch == '-') {
4616 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004617 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004618 *out++ = (char) ch;
4619 }
4620 else {
4621 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004622 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004623 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004624 else { /* not in a shift sequence */
4625 if (ch == '+') {
4626 *out++ = '+';
4627 *out++ = '-';
4628 }
4629 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4630 *out++ = (char) ch;
4631 }
4632 else {
4633 *out++ = '+';
4634 inShift = 1;
4635 goto encode_char;
4636 }
4637 }
4638 continue;
4639encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004640 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004641 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004642
Antoine Pitrou244651a2009-05-04 18:56:13 +00004643 /* code first surrogate */
4644 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004645 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004646 while (base64bits >= 6) {
4647 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4648 base64bits -= 6;
4649 }
4650 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004651 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004652 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004653 base64bits += 16;
4654 base64buffer = (base64buffer << 16) | ch;
4655 while (base64bits >= 6) {
4656 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4657 base64bits -= 6;
4658 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004659 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004660 if (base64bits)
4661 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4662 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004663 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004664 if (_PyBytes_Resize(&v, out - start) < 0)
4665 return NULL;
4666 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004667}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004668PyObject *
4669PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4670 Py_ssize_t size,
4671 int base64SetO,
4672 int base64WhiteSpace,
4673 const char *errors)
4674{
4675 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004676 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004677 if (tmp == NULL)
4678 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004679 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004680 base64WhiteSpace, errors);
4681 Py_DECREF(tmp);
4682 return result;
4683}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004684
Antoine Pitrou244651a2009-05-04 18:56:13 +00004685#undef IS_BASE64
4686#undef FROM_BASE64
4687#undef TO_BASE64
4688#undef DECODE_DIRECT
4689#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004690
Guido van Rossumd57fd912000-03-10 22:53:23 +00004691/* --- UTF-8 Codec -------------------------------------------------------- */
4692
Alexander Belopolsky40018472011-02-26 01:02:56 +00004693PyObject *
4694PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004695 Py_ssize_t size,
4696 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004697{
Walter Dörwald69652032004-09-07 20:24:22 +00004698 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4699}
4700
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004701#include "stringlib/asciilib.h"
4702#include "stringlib/codecs.h"
4703#include "stringlib/undef.h"
4704
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004705#include "stringlib/ucs1lib.h"
4706#include "stringlib/codecs.h"
4707#include "stringlib/undef.h"
4708
4709#include "stringlib/ucs2lib.h"
4710#include "stringlib/codecs.h"
4711#include "stringlib/undef.h"
4712
4713#include "stringlib/ucs4lib.h"
4714#include "stringlib/codecs.h"
4715#include "stringlib/undef.h"
4716
Antoine Pitrouab868312009-01-10 15:40:25 +00004717/* Mask to quickly check whether a C 'long' contains a
4718 non-ASCII, UTF8-encoded char. */
4719#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004720# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004721#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004722# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004723#else
4724# error C 'long' size should be either 4 or 8!
4725#endif
4726
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004727static Py_ssize_t
4728ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004729{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004730 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004731 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004732
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004733 /*
4734 * Issue #17237: m68k is a bit different from most architectures in
4735 * that objects do not use "natural alignment" - for example, int and
4736 * long are only aligned at 2-byte boundaries. Therefore the assert()
4737 * won't work; also, tests have shown that skipping the "optimised
4738 * version" will even speed up m68k.
4739 */
4740#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004741#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004742 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4743 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004744 /* Fast path, see in STRINGLIB(utf8_decode) for
4745 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004746 /* Help allocation */
4747 const char *_p = p;
4748 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004749 while (_p < aligned_end) {
4750 unsigned long value = *(const unsigned long *) _p;
4751 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004752 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004753 *((unsigned long *)q) = value;
4754 _p += SIZEOF_LONG;
4755 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004756 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004757 p = _p;
4758 while (p < end) {
4759 if ((unsigned char)*p & 0x80)
4760 break;
4761 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004762 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004763 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004764 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004765#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004766#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004767 while (p < end) {
4768 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4769 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004770 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004771 /* Help allocation */
4772 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004773 while (_p < aligned_end) {
4774 unsigned long value = *(unsigned long *) _p;
4775 if (value & ASCII_CHAR_MASK)
4776 break;
4777 _p += SIZEOF_LONG;
4778 }
4779 p = _p;
4780 if (_p == end)
4781 break;
4782 }
4783 if ((unsigned char)*p & 0x80)
4784 break;
4785 ++p;
4786 }
4787 memcpy(dest, start, p - start);
4788 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004789}
Antoine Pitrouab868312009-01-10 15:40:25 +00004790
Victor Stinner785938e2011-12-11 20:09:03 +01004791PyObject *
4792PyUnicode_DecodeUTF8Stateful(const char *s,
4793 Py_ssize_t size,
4794 const char *errors,
4795 Py_ssize_t *consumed)
4796{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004797 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004798 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004799 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800
4801 Py_ssize_t startinpos;
4802 Py_ssize_t endinpos;
4803 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004804 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004805 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004806 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004807
4808 if (size == 0) {
4809 if (consumed)
4810 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004811 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004812 }
4813
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004814 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4815 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004816 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004817 *consumed = 1;
4818 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004819 }
4820
Victor Stinner8f674cc2013-04-17 23:02:17 +02004821 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004822 writer.min_length = size;
4823 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004824 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004825
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004826 writer.pos = ascii_decode(s, end, writer.data);
4827 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004828 while (s < end) {
4829 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004830 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004831
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004832 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004833 if (PyUnicode_IS_ASCII(writer.buffer))
4834 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004835 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004836 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004837 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004838 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004839 } else {
4840 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004841 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004842 }
4843
4844 switch (ch) {
4845 case 0:
4846 if (s == end || consumed)
4847 goto End;
4848 errmsg = "unexpected end of data";
4849 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004850 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004851 break;
4852 case 1:
4853 errmsg = "invalid start byte";
4854 startinpos = s - starts;
4855 endinpos = startinpos + 1;
4856 break;
4857 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004858 case 3:
4859 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004860 errmsg = "invalid continuation byte";
4861 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004862 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004863 break;
4864 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004865 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004866 goto onError;
4867 continue;
4868 }
4869
Victor Stinner1d65d912015-10-05 13:43:50 +02004870 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02004871 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner1d65d912015-10-05 13:43:50 +02004872
4873 switch (error_handler) {
4874 case _Py_ERROR_IGNORE:
4875 s += (endinpos - startinpos);
4876 break;
4877
4878 case _Py_ERROR_REPLACE:
4879 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4880 goto onError;
4881 s += (endinpos - startinpos);
4882 break;
4883
4884 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004885 {
4886 Py_ssize_t i;
4887
Victor Stinner1d65d912015-10-05 13:43:50 +02004888 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4889 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004890 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004891 ch = (Py_UCS4)(unsigned char)(starts[i]);
4892 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4893 ch + 0xdc00);
4894 writer.pos++;
4895 }
4896 s += (endinpos - startinpos);
4897 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004898 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004899
4900 default:
4901 if (unicode_decode_call_errorhandler_writer(
4902 errors, &error_handler_obj,
4903 "utf-8", errmsg,
4904 &starts, &end, &startinpos, &endinpos, &exc, &s,
4905 &writer))
4906 goto onError;
4907 }
Victor Stinner785938e2011-12-11 20:09:03 +01004908 }
4909
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004910End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911 if (consumed)
4912 *consumed = s - starts;
4913
Victor Stinner1d65d912015-10-05 13:43:50 +02004914 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004915 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004916 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004917
4918onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004919 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004920 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004921 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004922 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004923}
4924
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004925
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004926/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4927 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004928
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004929 On success, write a pointer to a newly allocated wide character string into
4930 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4931 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004932
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004933 On memory allocation failure, return -1.
4934
4935 On decoding error (if surrogateescape is zero), return -2. If wlen is
4936 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4937 is not NULL, write the decoding error message into *reason. */
4938int
4939_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
Victor Stinner3d4226a2018-08-29 22:21:32 +02004940 const char **reason, _Py_error_handler errors)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004941{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004942 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004943 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004944 wchar_t *unicode;
4945 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004946
Victor Stinner3d4226a2018-08-29 22:21:32 +02004947 int surrogateescape = 0;
4948 int surrogatepass = 0;
4949 switch (errors)
4950 {
4951 case _Py_ERROR_STRICT:
4952 break;
4953 case _Py_ERROR_SURROGATEESCAPE:
4954 surrogateescape = 1;
4955 break;
4956 case _Py_ERROR_SURROGATEPASS:
4957 surrogatepass = 1;
4958 break;
4959 default:
4960 return -3;
4961 }
4962
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004963 /* Note: size will always be longer than the resulting Unicode
4964 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004965 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004966 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004967 }
4968
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004969 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004970 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004971 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004972 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004973
4974 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004975 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004976 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004977 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004978 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004979#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004980 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004981#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004982 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004983#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004984 if (ch > 0xFF) {
4985#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07004986 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004987#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02004988 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004989 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004990 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4991 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4992#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004993 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004994 else {
Victor Stinner3d4226a2018-08-29 22:21:32 +02004995 if (!ch && s == e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004996 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004997 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02004998
4999 if (surrogateescape) {
5000 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5001 }
5002 else {
5003 /* Is it a valid three-byte code? */
5004 if (surrogatepass
5005 && (e - s) >= 3
5006 && (s[0] & 0xf0) == 0xe0
5007 && (s[1] & 0xc0) == 0x80
5008 && (s[2] & 0xc0) == 0x80)
5009 {
5010 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5011 s += 3;
5012 unicode[outpos++] = ch;
5013 }
5014 else {
5015 PyMem_RawFree(unicode );
5016 if (reason != NULL) {
5017 switch (ch) {
5018 case 0:
5019 *reason = "unexpected end of data";
5020 break;
5021 case 1:
5022 *reason = "invalid start byte";
5023 break;
5024 /* 2, 3, 4 */
5025 default:
5026 *reason = "invalid continuation byte";
5027 break;
5028 }
5029 }
5030 if (wlen != NULL) {
5031 *wlen = s - orig_s;
5032 }
5033 return -2;
5034 }
5035 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005036 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005037 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005038 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005039 if (wlen) {
5040 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005041 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005042 *wstr = unicode;
5043 return 0;
5044}
5045
5046wchar_t*
5047_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen)
5048{
5049 wchar_t *wstr;
5050 int res = _Py_DecodeUTF8Ex(arg, arglen, &wstr, NULL, NULL, 1);
5051 if (res != 0) {
5052 return NULL;
5053 }
5054 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005055}
5056
Antoine Pitrouab868312009-01-10 15:40:25 +00005057
Victor Stinnere47e6982017-12-21 15:45:16 +01005058/* UTF-8 encoder using the surrogateescape error handler .
5059
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005060 On success, return 0 and write the newly allocated character string (use
5061 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005062
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005063 On encoding failure, return -2 and write the position of the invalid
5064 surrogate character into *error_pos (if error_pos is set) and the decoding
5065 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005066
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005067 On memory allocation failure, return -1. */
5068int
5069_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005070 const char **reason, int raw_malloc, _Py_error_handler errors)
Victor Stinnere47e6982017-12-21 15:45:16 +01005071{
5072 const Py_ssize_t max_char_size = 4;
5073 Py_ssize_t len = wcslen(text);
5074
5075 assert(len >= 0);
5076
Victor Stinner3d4226a2018-08-29 22:21:32 +02005077 int surrogateescape = 0;
5078 int surrogatepass = 0;
5079 switch (errors)
5080 {
5081 case _Py_ERROR_STRICT:
5082 break;
5083 case _Py_ERROR_SURROGATEESCAPE:
5084 surrogateescape = 1;
5085 break;
5086 case _Py_ERROR_SURROGATEPASS:
5087 surrogatepass = 1;
5088 break;
5089 default:
5090 return -3;
5091 }
5092
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005093 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5094 return -1;
5095 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005096 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005097 if (raw_malloc) {
5098 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005099 }
5100 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005101 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005102 }
5103 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005104 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005105 }
5106
5107 char *p = bytes;
5108 Py_ssize_t i;
Victor Stinner3d4226a2018-08-29 22:21:32 +02005109 for (i = 0; i < len; ) {
5110 Py_ssize_t ch_pos = i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005111 Py_UCS4 ch = text[i];
Victor Stinner3d4226a2018-08-29 22:21:32 +02005112 i++;
5113#if Py_UNICODE_SIZE == 2
5114 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
5115 && i < len
5116 && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5117 {
5118 ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5119 i++;
5120 }
5121#endif
Victor Stinnere47e6982017-12-21 15:45:16 +01005122
5123 if (ch < 0x80) {
5124 /* Encode ASCII */
5125 *p++ = (char) ch;
5126
5127 }
5128 else if (ch < 0x0800) {
5129 /* Encode Latin-1 */
5130 *p++ = (char)(0xc0 | (ch >> 6));
5131 *p++ = (char)(0x80 | (ch & 0x3f));
5132 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005133 else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005134 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005135 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005136 if (error_pos != NULL) {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005137 *error_pos = (size_t)ch_pos;
Victor Stinnere47e6982017-12-21 15:45:16 +01005138 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005139 if (reason != NULL) {
5140 *reason = "encoding error";
5141 }
5142 if (raw_malloc) {
5143 PyMem_RawFree(bytes);
5144 }
5145 else {
5146 PyMem_Free(bytes);
5147 }
5148 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005149 }
5150 *p++ = (char)(ch & 0xff);
5151 }
5152 else if (ch < 0x10000) {
5153 *p++ = (char)(0xe0 | (ch >> 12));
5154 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5155 *p++ = (char)(0x80 | (ch & 0x3f));
5156 }
5157 else { /* ch >= 0x10000 */
5158 assert(ch <= MAX_UNICODE);
5159 /* Encode UCS4 Unicode ordinals */
5160 *p++ = (char)(0xf0 | (ch >> 18));
5161 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5162 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5163 *p++ = (char)(0x80 | (ch & 0x3f));
5164 }
5165 }
5166 *p++ = '\0';
5167
5168 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005169 char *bytes2;
5170 if (raw_malloc) {
5171 bytes2 = PyMem_RawRealloc(bytes, final_size);
5172 }
5173 else {
5174 bytes2 = PyMem_Realloc(bytes, final_size);
5175 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005176 if (bytes2 == NULL) {
5177 if (error_pos != NULL) {
5178 *error_pos = (size_t)-1;
5179 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005180 if (raw_malloc) {
5181 PyMem_RawFree(bytes);
5182 }
5183 else {
5184 PyMem_Free(bytes);
5185 }
5186 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005187 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005188 *str = bytes2;
5189 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005190}
5191
5192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005193/* Primary internal function which creates utf8 encoded bytes objects.
5194
5195 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005196 and allocate exactly as much space needed at the end. Else allocate the
5197 maximum possible needed (4 result bytes per Unicode character), and return
5198 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005199*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005200PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005201_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005202{
Victor Stinner6099a032011-12-18 14:22:26 +01005203 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005204 void *data;
5205 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005206
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005207 if (!PyUnicode_Check(unicode)) {
5208 PyErr_BadArgument();
5209 return NULL;
5210 }
5211
5212 if (PyUnicode_READY(unicode) == -1)
5213 return NULL;
5214
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005215 if (PyUnicode_UTF8(unicode))
5216 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5217 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005218
5219 kind = PyUnicode_KIND(unicode);
5220 data = PyUnicode_DATA(unicode);
5221 size = PyUnicode_GET_LENGTH(unicode);
5222
Benjamin Petersonead6b532011-12-20 17:23:42 -06005223 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005224 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005225 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005226 case PyUnicode_1BYTE_KIND:
5227 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5228 assert(!PyUnicode_IS_ASCII(unicode));
5229 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5230 case PyUnicode_2BYTE_KIND:
5231 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5232 case PyUnicode_4BYTE_KIND:
5233 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005234 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005235}
5236
Alexander Belopolsky40018472011-02-26 01:02:56 +00005237PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005238PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5239 Py_ssize_t size,
5240 const char *errors)
5241{
5242 PyObject *v, *unicode;
5243
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005244 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005245 if (unicode == NULL)
5246 return NULL;
5247 v = _PyUnicode_AsUTF8String(unicode, errors);
5248 Py_DECREF(unicode);
5249 return v;
5250}
5251
5252PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005253PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005254{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005255 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005256}
5257
Walter Dörwald41980ca2007-08-16 21:55:45 +00005258/* --- UTF-32 Codec ------------------------------------------------------- */
5259
5260PyObject *
5261PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005262 Py_ssize_t size,
5263 const char *errors,
5264 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005265{
5266 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5267}
5268
5269PyObject *
5270PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005271 Py_ssize_t size,
5272 const char *errors,
5273 int *byteorder,
5274 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005275{
5276 const char *starts = s;
5277 Py_ssize_t startinpos;
5278 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005279 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005280 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005281 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005282 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005283 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005284 PyObject *errorHandler = NULL;
5285 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005286
Walter Dörwald41980ca2007-08-16 21:55:45 +00005287 q = (unsigned char *)s;
5288 e = q + size;
5289
5290 if (byteorder)
5291 bo = *byteorder;
5292
5293 /* Check for BOM marks (U+FEFF) in the input and adjust current
5294 byte order setting accordingly. In native mode, the leading BOM
5295 mark is skipped, in all other modes, it is copied to the output
5296 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005297 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005298 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005299 if (bom == 0x0000FEFF) {
5300 bo = -1;
5301 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005302 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005303 else if (bom == 0xFFFE0000) {
5304 bo = 1;
5305 q += 4;
5306 }
5307 if (byteorder)
5308 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005309 }
5310
Victor Stinnere64322e2012-10-30 23:12:47 +01005311 if (q == e) {
5312 if (consumed)
5313 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005314 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005315 }
5316
Victor Stinnere64322e2012-10-30 23:12:47 +01005317#ifdef WORDS_BIGENDIAN
5318 le = bo < 0;
5319#else
5320 le = bo <= 0;
5321#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005322 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005323
Victor Stinner8f674cc2013-04-17 23:02:17 +02005324 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005325 writer.min_length = (e - q + 3) / 4;
5326 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005327 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005328
Victor Stinnere64322e2012-10-30 23:12:47 +01005329 while (1) {
5330 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005331 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005332
Victor Stinnere64322e2012-10-30 23:12:47 +01005333 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005334 enum PyUnicode_Kind kind = writer.kind;
5335 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005336 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005337 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005338 if (le) {
5339 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005340 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005341 if (ch > maxch)
5342 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005343 if (kind != PyUnicode_1BYTE_KIND &&
5344 Py_UNICODE_IS_SURROGATE(ch))
5345 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005346 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005347 q += 4;
5348 } while (q <= last);
5349 }
5350 else {
5351 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005352 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005353 if (ch > maxch)
5354 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005355 if (kind != PyUnicode_1BYTE_KIND &&
5356 Py_UNICODE_IS_SURROGATE(ch))
5357 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005358 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005359 q += 4;
5360 } while (q <= last);
5361 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005362 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005363 }
5364
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005365 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005366 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005367 startinpos = ((const char *)q) - starts;
5368 endinpos = startinpos + 4;
5369 }
5370 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005371 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005372 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005373 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005374 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005375 startinpos = ((const char *)q) - starts;
5376 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005377 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005378 else {
5379 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005380 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005381 goto onError;
5382 q += 4;
5383 continue;
5384 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005385 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005386 startinpos = ((const char *)q) - starts;
5387 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005388 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005389
5390 /* The remaining input chars are ignored if the callback
5391 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005392 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005393 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005394 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005395 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005396 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005397 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005398 }
5399
Walter Dörwald41980ca2007-08-16 21:55:45 +00005400 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005401 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005402
Walter Dörwald41980ca2007-08-16 21:55:45 +00005403 Py_XDECREF(errorHandler);
5404 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005405 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005406
Benjamin Peterson29060642009-01-31 22:14:21 +00005407 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005408 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005409 Py_XDECREF(errorHandler);
5410 Py_XDECREF(exc);
5411 return NULL;
5412}
5413
5414PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005415_PyUnicode_EncodeUTF32(PyObject *str,
5416 const char *errors,
5417 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005418{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005419 enum PyUnicode_Kind kind;
5420 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005421 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005422 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005423 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005424#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005425 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005426#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005427 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005428#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005429 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005430 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005431 PyObject *errorHandler = NULL;
5432 PyObject *exc = NULL;
5433 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005434
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005435 if (!PyUnicode_Check(str)) {
5436 PyErr_BadArgument();
5437 return NULL;
5438 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005439 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005440 return NULL;
5441 kind = PyUnicode_KIND(str);
5442 data = PyUnicode_DATA(str);
5443 len = PyUnicode_GET_LENGTH(str);
5444
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005445 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005446 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005447 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005448 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005449 if (v == NULL)
5450 return NULL;
5451
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005452 /* output buffer is 4-bytes aligned */
5453 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005454 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005455 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005456 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005457 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005458 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005459
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005460 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005461 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005462 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005463 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005464 else
5465 encoding = "utf-32";
5466
5467 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005468 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5469 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005470 }
5471
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005472 pos = 0;
5473 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005474 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005475
5476 if (kind == PyUnicode_2BYTE_KIND) {
5477 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5478 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005479 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005480 else {
5481 assert(kind == PyUnicode_4BYTE_KIND);
5482 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5483 &out, native_ordering);
5484 }
5485 if (pos == len)
5486 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005487
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005488 rep = unicode_encode_call_errorhandler(
5489 errors, &errorHandler,
5490 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005491 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005492 if (!rep)
5493 goto error;
5494
5495 if (PyBytes_Check(rep)) {
5496 repsize = PyBytes_GET_SIZE(rep);
5497 if (repsize & 3) {
5498 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005499 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005500 "surrogates not allowed");
5501 goto error;
5502 }
5503 moreunits = repsize / 4;
5504 }
5505 else {
5506 assert(PyUnicode_Check(rep));
5507 if (PyUnicode_READY(rep) < 0)
5508 goto error;
5509 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5510 if (!PyUnicode_IS_ASCII(rep)) {
5511 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005512 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005513 "surrogates not allowed");
5514 goto error;
5515 }
5516 }
5517
5518 /* four bytes are reserved for each surrogate */
5519 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005520 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005521 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005522 /* integer overflow */
5523 PyErr_NoMemory();
5524 goto error;
5525 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005526 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005527 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005528 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005529 }
5530
5531 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005532 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005533 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005534 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005535 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005536 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5537 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005538 }
5539
5540 Py_CLEAR(rep);
5541 }
5542
5543 /* Cut back to size actually needed. This is necessary for, for example,
5544 encoding of a string containing isolated surrogates and the 'ignore'
5545 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005546 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005547 if (nsize != PyBytes_GET_SIZE(v))
5548 _PyBytes_Resize(&v, nsize);
5549 Py_XDECREF(errorHandler);
5550 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005551 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005552 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005553 error:
5554 Py_XDECREF(rep);
5555 Py_XDECREF(errorHandler);
5556 Py_XDECREF(exc);
5557 Py_XDECREF(v);
5558 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005559}
5560
Alexander Belopolsky40018472011-02-26 01:02:56 +00005561PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005562PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5563 Py_ssize_t size,
5564 const char *errors,
5565 int byteorder)
5566{
5567 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005568 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005569 if (tmp == NULL)
5570 return NULL;
5571 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5572 Py_DECREF(tmp);
5573 return result;
5574}
5575
5576PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005577PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005578{
Victor Stinnerb960b342011-11-20 19:12:52 +01005579 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005580}
5581
Guido van Rossumd57fd912000-03-10 22:53:23 +00005582/* --- UTF-16 Codec ------------------------------------------------------- */
5583
Tim Peters772747b2001-08-09 22:21:55 +00005584PyObject *
5585PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005586 Py_ssize_t size,
5587 const char *errors,
5588 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005589{
Walter Dörwald69652032004-09-07 20:24:22 +00005590 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5591}
5592
5593PyObject *
5594PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005595 Py_ssize_t size,
5596 const char *errors,
5597 int *byteorder,
5598 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005599{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005600 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005601 Py_ssize_t startinpos;
5602 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005603 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005604 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005605 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005606 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005607 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005608 PyObject *errorHandler = NULL;
5609 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005610 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611
Tim Peters772747b2001-08-09 22:21:55 +00005612 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005613 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614
5615 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005616 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005617
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005618 /* Check for BOM marks (U+FEFF) in the input and adjust current
5619 byte order setting accordingly. In native mode, the leading BOM
5620 mark is skipped, in all other modes, it is copied to the output
5621 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005622 if (bo == 0 && size >= 2) {
5623 const Py_UCS4 bom = (q[1] << 8) | q[0];
5624 if (bom == 0xFEFF) {
5625 q += 2;
5626 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005628 else if (bom == 0xFFFE) {
5629 q += 2;
5630 bo = 1;
5631 }
5632 if (byteorder)
5633 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005634 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005635
Antoine Pitrou63065d72012-05-15 23:48:04 +02005636 if (q == e) {
5637 if (consumed)
5638 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005639 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005640 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005641
Christian Heimes743e0cd2012-10-17 23:52:17 +02005642#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005643 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005644 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005645#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005646 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005647 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005648#endif
Tim Peters772747b2001-08-09 22:21:55 +00005649
Antoine Pitrou63065d72012-05-15 23:48:04 +02005650 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005651 character count normally. Error handler will take care of
5652 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005653 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005654 writer.min_length = (e - q + 1) / 2;
5655 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005656 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005657
Antoine Pitrou63065d72012-05-15 23:48:04 +02005658 while (1) {
5659 Py_UCS4 ch = 0;
5660 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005661 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005662 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005663 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005664 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005665 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005666 native_ordering);
5667 else
5668 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005669 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005670 native_ordering);
5671 } else if (kind == PyUnicode_2BYTE_KIND) {
5672 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005673 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005674 native_ordering);
5675 } else {
5676 assert(kind == PyUnicode_4BYTE_KIND);
5677 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005678 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005679 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005680 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005681 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005682
Antoine Pitrou63065d72012-05-15 23:48:04 +02005683 switch (ch)
5684 {
5685 case 0:
5686 /* remaining byte at the end? (size should be even) */
5687 if (q == e || consumed)
5688 goto End;
5689 errmsg = "truncated data";
5690 startinpos = ((const char *)q) - starts;
5691 endinpos = ((const char *)e) - starts;
5692 break;
5693 /* The remaining input chars are ignored if the callback
5694 chooses to skip the input */
5695 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005696 q -= 2;
5697 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005698 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005699 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005700 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005701 endinpos = ((const char *)e) - starts;
5702 break;
5703 case 2:
5704 errmsg = "illegal encoding";
5705 startinpos = ((const char *)q) - 2 - starts;
5706 endinpos = startinpos + 2;
5707 break;
5708 case 3:
5709 errmsg = "illegal UTF-16 surrogate";
5710 startinpos = ((const char *)q) - 4 - starts;
5711 endinpos = startinpos + 2;
5712 break;
5713 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005714 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005715 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005716 continue;
5717 }
5718
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005719 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005720 errors,
5721 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005722 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005723 &starts,
5724 (const char **)&e,
5725 &startinpos,
5726 &endinpos,
5727 &exc,
5728 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005729 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731 }
5732
Antoine Pitrou63065d72012-05-15 23:48:04 +02005733End:
Walter Dörwald69652032004-09-07 20:24:22 +00005734 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005736
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005737 Py_XDECREF(errorHandler);
5738 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005739 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005740
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005742 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005743 Py_XDECREF(errorHandler);
5744 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005745 return NULL;
5746}
5747
Tim Peters772747b2001-08-09 22:21:55 +00005748PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005749_PyUnicode_EncodeUTF16(PyObject *str,
5750 const char *errors,
5751 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005752{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005753 enum PyUnicode_Kind kind;
5754 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005755 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005756 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005757 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005758 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005759#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005760 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005761#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005762 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005763#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005764 const char *encoding;
5765 Py_ssize_t nsize, pos;
5766 PyObject *errorHandler = NULL;
5767 PyObject *exc = NULL;
5768 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005769
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005770 if (!PyUnicode_Check(str)) {
5771 PyErr_BadArgument();
5772 return NULL;
5773 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005774 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005775 return NULL;
5776 kind = PyUnicode_KIND(str);
5777 data = PyUnicode_DATA(str);
5778 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005779
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005780 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005781 if (kind == PyUnicode_4BYTE_KIND) {
5782 const Py_UCS4 *in = (const Py_UCS4 *)data;
5783 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005784 while (in < end) {
5785 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005786 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005787 }
5788 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005789 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005790 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005791 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005792 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005793 nsize = len + pairs + (byteorder == 0);
5794 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005795 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005796 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005797 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005798
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005799 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005800 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005801 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005802 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005803 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005804 }
5805 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005806 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005807 }
Tim Peters772747b2001-08-09 22:21:55 +00005808
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005809 if (kind == PyUnicode_1BYTE_KIND) {
5810 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5811 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005812 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005813
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005814 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005815 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005816 }
5817 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005818 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005819 }
5820 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005821 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005822 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005823
5824 pos = 0;
5825 while (pos < len) {
5826 Py_ssize_t repsize, moreunits;
5827
5828 if (kind == PyUnicode_2BYTE_KIND) {
5829 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5830 &out, native_ordering);
5831 }
5832 else {
5833 assert(kind == PyUnicode_4BYTE_KIND);
5834 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5835 &out, native_ordering);
5836 }
5837 if (pos == len)
5838 break;
5839
5840 rep = unicode_encode_call_errorhandler(
5841 errors, &errorHandler,
5842 encoding, "surrogates not allowed",
5843 str, &exc, pos, pos + 1, &pos);
5844 if (!rep)
5845 goto error;
5846
5847 if (PyBytes_Check(rep)) {
5848 repsize = PyBytes_GET_SIZE(rep);
5849 if (repsize & 1) {
5850 raise_encode_exception(&exc, encoding,
5851 str, pos - 1, pos,
5852 "surrogates not allowed");
5853 goto error;
5854 }
5855 moreunits = repsize / 2;
5856 }
5857 else {
5858 assert(PyUnicode_Check(rep));
5859 if (PyUnicode_READY(rep) < 0)
5860 goto error;
5861 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5862 if (!PyUnicode_IS_ASCII(rep)) {
5863 raise_encode_exception(&exc, encoding,
5864 str, pos - 1, pos,
5865 "surrogates not allowed");
5866 goto error;
5867 }
5868 }
5869
5870 /* two bytes are reserved for each surrogate */
5871 if (moreunits > 1) {
5872 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005873 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005874 /* integer overflow */
5875 PyErr_NoMemory();
5876 goto error;
5877 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005878 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005879 goto error;
5880 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5881 }
5882
5883 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005884 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005885 out += moreunits;
5886 } else /* rep is unicode */ {
5887 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5888 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5889 &out, native_ordering);
5890 }
5891
5892 Py_CLEAR(rep);
5893 }
5894
5895 /* Cut back to size actually needed. This is necessary for, for example,
5896 encoding of a string containing isolated surrogates and the 'ignore' handler
5897 is used. */
5898 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5899 if (nsize != PyBytes_GET_SIZE(v))
5900 _PyBytes_Resize(&v, nsize);
5901 Py_XDECREF(errorHandler);
5902 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005903 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005904 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005905 error:
5906 Py_XDECREF(rep);
5907 Py_XDECREF(errorHandler);
5908 Py_XDECREF(exc);
5909 Py_XDECREF(v);
5910 return NULL;
5911#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005912}
5913
Alexander Belopolsky40018472011-02-26 01:02:56 +00005914PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005915PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5916 Py_ssize_t size,
5917 const char *errors,
5918 int byteorder)
5919{
5920 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005921 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005922 if (tmp == NULL)
5923 return NULL;
5924 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5925 Py_DECREF(tmp);
5926 return result;
5927}
5928
5929PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005930PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005932 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933}
5934
5935/* --- Unicode Escape Codec ----------------------------------------------- */
5936
Fredrik Lundh06d12682001-01-24 07:59:11 +00005937static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005938
Alexander Belopolsky40018472011-02-26 01:02:56 +00005939PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005940_PyUnicode_DecodeUnicodeEscape(const char *s,
5941 Py_ssize_t size,
5942 const char *errors,
5943 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005944{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005945 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005946 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005947 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005948 PyObject *errorHandler = NULL;
5949 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005950
Eric V. Smith42454af2016-10-31 09:22:08 -04005951 // so we can remember if we've seen an invalid escape char or not
5952 *first_invalid_escape = NULL;
5953
Victor Stinner62ec3312016-09-06 17:04:34 -07005954 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005955 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005956 }
5957 /* Escaped strings will always be longer than the resulting
5958 Unicode string, so we start with size here and then reduce the
5959 length after conversion to the true value.
5960 (but if the error callback returns a long replacement string
5961 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005962 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005963 writer.min_length = size;
5964 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5965 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005966 }
5967
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 end = s + size;
5969 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005970 unsigned char c = (unsigned char) *s++;
5971 Py_UCS4 ch;
5972 int count;
5973 Py_ssize_t startinpos;
5974 Py_ssize_t endinpos;
5975 const char *message;
5976
5977#define WRITE_ASCII_CHAR(ch) \
5978 do { \
5979 assert(ch <= 127); \
5980 assert(writer.pos < writer.size); \
5981 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5982 } while(0)
5983
5984#define WRITE_CHAR(ch) \
5985 do { \
5986 if (ch <= writer.maxchar) { \
5987 assert(writer.pos < writer.size); \
5988 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5989 } \
5990 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5991 goto onError; \
5992 } \
5993 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005994
5995 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005996 if (c != '\\') {
5997 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998 continue;
5999 }
6000
Victor Stinner62ec3312016-09-06 17:04:34 -07006001 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006002 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006003 if (s >= end) {
6004 message = "\\ at end of string";
6005 goto error;
6006 }
6007 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006008
Victor Stinner62ec3312016-09-06 17:04:34 -07006009 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006010 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006011
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006013 case '\n': continue;
6014 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6015 case '\'': WRITE_ASCII_CHAR('\''); continue;
6016 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6017 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006018 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006019 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6020 case 't': WRITE_ASCII_CHAR('\t'); continue;
6021 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6022 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006023 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006024 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006025 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006026 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027
Benjamin Peterson29060642009-01-31 22:14:21 +00006028 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 case '0': case '1': case '2': case '3':
6030 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006031 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006032 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006033 ch = (ch<<3) + *s++ - '0';
6034 if (s < end && '0' <= *s && *s <= '7') {
6035 ch = (ch<<3) + *s++ - '0';
6036 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006037 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006038 WRITE_CHAR(ch);
6039 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006040
Benjamin Peterson29060642009-01-31 22:14:21 +00006041 /* hex escapes */
6042 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006043 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006044 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006045 message = "truncated \\xXX escape";
6046 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047
Benjamin Peterson29060642009-01-31 22:14:21 +00006048 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006049 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006050 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006051 message = "truncated \\uXXXX escape";
6052 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006053
Benjamin Peterson29060642009-01-31 22:14:21 +00006054 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006055 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006056 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006057 message = "truncated \\UXXXXXXXX escape";
6058 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006059 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006060 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006061 ch <<= 4;
6062 if (c >= '0' && c <= '9') {
6063 ch += c - '0';
6064 }
6065 else if (c >= 'a' && c <= 'f') {
6066 ch += c - ('a' - 10);
6067 }
6068 else if (c >= 'A' && c <= 'F') {
6069 ch += c - ('A' - 10);
6070 }
6071 else {
6072 break;
6073 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006074 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006075 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006076 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006077 }
6078
6079 /* when we get here, ch is a 32-bit unicode character */
6080 if (ch > MAX_UNICODE) {
6081 message = "illegal Unicode character";
6082 goto error;
6083 }
6084
6085 WRITE_CHAR(ch);
6086 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006087
Benjamin Peterson29060642009-01-31 22:14:21 +00006088 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006089 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006090 if (ucnhash_CAPI == NULL) {
6091 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006092 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6093 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006094 if (ucnhash_CAPI == NULL) {
6095 PyErr_SetString(
6096 PyExc_UnicodeError,
6097 "\\N escapes not supported (can't load unicodedata module)"
6098 );
6099 goto onError;
6100 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006101 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006102
6103 message = "malformed \\N character escape";
Gregory P. Smith746b2d32018-11-13 13:16:54 -08006104 if (s < end && *s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006105 const char *start = ++s;
6106 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006107 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006108 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006109 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006110 namelen = s - start;
6111 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006112 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006113 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006114 ch = 0xffffffff; /* in case 'getcode' messes up */
6115 if (namelen <= INT_MAX &&
6116 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6117 &ch, 0)) {
6118 assert(ch <= MAX_UNICODE);
6119 WRITE_CHAR(ch);
6120 continue;
6121 }
6122 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006123 }
6124 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006125 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006126
6127 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006128 if (*first_invalid_escape == NULL) {
6129 *first_invalid_escape = s-1; /* Back up one char, since we've
6130 already incremented s. */
6131 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006132 WRITE_ASCII_CHAR('\\');
6133 WRITE_CHAR(c);
6134 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006135 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006136
6137 error:
6138 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006139 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006140 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006141 errors, &errorHandler,
6142 "unicodeescape", message,
6143 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006144 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006145 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006146 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006147 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006148
6149#undef WRITE_ASCII_CHAR
6150#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006151 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006152
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006153 Py_XDECREF(errorHandler);
6154 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006155 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006156
Benjamin Peterson29060642009-01-31 22:14:21 +00006157 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006158 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006159 Py_XDECREF(errorHandler);
6160 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006161 return NULL;
6162}
6163
Eric V. Smith42454af2016-10-31 09:22:08 -04006164PyObject *
6165PyUnicode_DecodeUnicodeEscape(const char *s,
6166 Py_ssize_t size,
6167 const char *errors)
6168{
6169 const char *first_invalid_escape;
6170 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6171 &first_invalid_escape);
6172 if (result == NULL)
6173 return NULL;
6174 if (first_invalid_escape != NULL) {
6175 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6176 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006177 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006178 Py_DECREF(result);
6179 return NULL;
6180 }
6181 }
6182 return result;
6183}
6184
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006185/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006186
Alexander Belopolsky40018472011-02-26 01:02:56 +00006187PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006188PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006189{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006190 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006191 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006192 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006193 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006194 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006195 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006196
Ezio Melottie7f90372012-10-05 03:33:31 +03006197 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006198 escape.
6199
Ezio Melottie7f90372012-10-05 03:33:31 +03006200 For UCS1 strings it's '\xxx', 4 bytes per source character.
6201 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6202 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006203 */
6204
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006205 if (!PyUnicode_Check(unicode)) {
6206 PyErr_BadArgument();
6207 return NULL;
6208 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006209 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006210 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006211 }
Victor Stinner358af132015-10-12 22:36:57 +02006212
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006213 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006214 if (len == 0) {
6215 return PyBytes_FromStringAndSize(NULL, 0);
6216 }
6217
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006218 kind = PyUnicode_KIND(unicode);
6219 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006220 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6221 bytes, and 1 byte characters 4. */
6222 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006223 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006224 return PyErr_NoMemory();
6225 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006226 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006227 if (repr == NULL) {
6228 return NULL;
6229 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006230
Victor Stinner62ec3312016-09-06 17:04:34 -07006231 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006232 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006233 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006234
Victor Stinner62ec3312016-09-06 17:04:34 -07006235 /* U+0000-U+00ff range */
6236 if (ch < 0x100) {
6237 if (ch >= ' ' && ch < 127) {
6238 if (ch != '\\') {
6239 /* Copy printable US ASCII as-is */
6240 *p++ = (char) ch;
6241 }
6242 /* Escape backslashes */
6243 else {
6244 *p++ = '\\';
6245 *p++ = '\\';
6246 }
6247 }
Victor Stinner358af132015-10-12 22:36:57 +02006248
Victor Stinner62ec3312016-09-06 17:04:34 -07006249 /* Map special whitespace to '\t', \n', '\r' */
6250 else if (ch == '\t') {
6251 *p++ = '\\';
6252 *p++ = 't';
6253 }
6254 else if (ch == '\n') {
6255 *p++ = '\\';
6256 *p++ = 'n';
6257 }
6258 else if (ch == '\r') {
6259 *p++ = '\\';
6260 *p++ = 'r';
6261 }
6262
6263 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6264 else {
6265 *p++ = '\\';
6266 *p++ = 'x';
6267 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6268 *p++ = Py_hexdigits[ch & 0x000F];
6269 }
Tim Petersced69f82003-09-16 20:30:58 +00006270 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006271 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006272 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006273 *p++ = '\\';
6274 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006275 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6276 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6277 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6278 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006279 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006280 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6281 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006282
Victor Stinner62ec3312016-09-06 17:04:34 -07006283 /* Make sure that the first two digits are zero */
6284 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006285 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006286 *p++ = 'U';
6287 *p++ = '0';
6288 *p++ = '0';
6289 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6290 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6291 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6292 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6293 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6294 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006295 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006297
Victor Stinner62ec3312016-09-06 17:04:34 -07006298 assert(p - PyBytes_AS_STRING(repr) > 0);
6299 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6300 return NULL;
6301 }
6302 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303}
6304
Alexander Belopolsky40018472011-02-26 01:02:56 +00006305PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006306PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6307 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006309 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006310 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006311 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006312 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006313 }
6314
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006315 result = PyUnicode_AsUnicodeEscapeString(tmp);
6316 Py_DECREF(tmp);
6317 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006318}
6319
6320/* --- Raw Unicode Escape Codec ------------------------------------------- */
6321
Alexander Belopolsky40018472011-02-26 01:02:56 +00006322PyObject *
6323PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006324 Py_ssize_t size,
6325 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006326{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006327 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006328 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006329 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006330 PyObject *errorHandler = NULL;
6331 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006332
Victor Stinner62ec3312016-09-06 17:04:34 -07006333 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006334 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006335 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006336
Guido van Rossumd57fd912000-03-10 22:53:23 +00006337 /* Escaped strings will always be longer than the resulting
6338 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006339 length after conversion to the true value. (But decoding error
6340 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006341 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006342 writer.min_length = size;
6343 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6344 goto onError;
6345 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006346
Guido van Rossumd57fd912000-03-10 22:53:23 +00006347 end = s + size;
6348 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006349 unsigned char c = (unsigned char) *s++;
6350 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006351 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006352 Py_ssize_t startinpos;
6353 Py_ssize_t endinpos;
6354 const char *message;
6355
6356#define WRITE_CHAR(ch) \
6357 do { \
6358 if (ch <= writer.maxchar) { \
6359 assert(writer.pos < writer.size); \
6360 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6361 } \
6362 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6363 goto onError; \
6364 } \
6365 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006366
Benjamin Peterson29060642009-01-31 22:14:21 +00006367 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006368 if (c != '\\' || s >= end) {
6369 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006370 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006371 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006372
Victor Stinner62ec3312016-09-06 17:04:34 -07006373 c = (unsigned char) *s++;
6374 if (c == 'u') {
6375 count = 4;
6376 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006377 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006378 else if (c == 'U') {
6379 count = 8;
6380 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006381 }
6382 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006383 assert(writer.pos < writer.size);
6384 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6385 WRITE_CHAR(c);
6386 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006387 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006388 startinpos = s - starts - 2;
6389
6390 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6391 for (ch = 0; count && s < end; ++s, --count) {
6392 c = (unsigned char)*s;
6393 ch <<= 4;
6394 if (c >= '0' && c <= '9') {
6395 ch += c - '0';
6396 }
6397 else if (c >= 'a' && c <= 'f') {
6398 ch += c - ('a' - 10);
6399 }
6400 else if (c >= 'A' && c <= 'F') {
6401 ch += c - ('A' - 10);
6402 }
6403 else {
6404 break;
6405 }
6406 }
6407 if (!count) {
6408 if (ch <= MAX_UNICODE) {
6409 WRITE_CHAR(ch);
6410 continue;
6411 }
6412 message = "\\Uxxxxxxxx out of range";
6413 }
6414
6415 endinpos = s-starts;
6416 writer.min_length = end - s + writer.pos;
6417 if (unicode_decode_call_errorhandler_writer(
6418 errors, &errorHandler,
6419 "rawunicodeescape", message,
6420 &starts, &end, &startinpos, &endinpos, &exc, &s,
6421 &writer)) {
6422 goto onError;
6423 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006424 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006425
6426#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428 Py_XDECREF(errorHandler);
6429 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006430 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006431
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006433 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 Py_XDECREF(errorHandler);
6435 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006436 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006437
Guido van Rossumd57fd912000-03-10 22:53:23 +00006438}
6439
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006440
Alexander Belopolsky40018472011-02-26 01:02:56 +00006441PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006442PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006443{
Victor Stinner62ec3312016-09-06 17:04:34 -07006444 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006445 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006446 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006447 int kind;
6448 void *data;
6449 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006450
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006451 if (!PyUnicode_Check(unicode)) {
6452 PyErr_BadArgument();
6453 return NULL;
6454 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006455 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006456 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006457 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006458 kind = PyUnicode_KIND(unicode);
6459 data = PyUnicode_DATA(unicode);
6460 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006461 if (kind == PyUnicode_1BYTE_KIND) {
6462 return PyBytes_FromStringAndSize(data, len);
6463 }
Victor Stinner0e368262011-11-10 20:12:49 +01006464
Victor Stinner62ec3312016-09-06 17:04:34 -07006465 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6466 bytes, and 1 byte characters 4. */
6467 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006468
Victor Stinner62ec3312016-09-06 17:04:34 -07006469 if (len > PY_SSIZE_T_MAX / expandsize) {
6470 return PyErr_NoMemory();
6471 }
6472 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6473 if (repr == NULL) {
6474 return NULL;
6475 }
6476 if (len == 0) {
6477 return repr;
6478 }
6479
6480 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006481 for (pos = 0; pos < len; pos++) {
6482 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006483
Victor Stinner62ec3312016-09-06 17:04:34 -07006484 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6485 if (ch < 0x100) {
6486 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006487 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006488 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006489 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006490 *p++ = '\\';
6491 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006492 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6493 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6494 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6495 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006496 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006497 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6498 else {
6499 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6500 *p++ = '\\';
6501 *p++ = 'U';
6502 *p++ = '0';
6503 *p++ = '0';
6504 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6505 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6506 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6507 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6508 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6509 *p++ = Py_hexdigits[ch & 15];
6510 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006511 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006512
Victor Stinner62ec3312016-09-06 17:04:34 -07006513 assert(p > PyBytes_AS_STRING(repr));
6514 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6515 return NULL;
6516 }
6517 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006518}
6519
Alexander Belopolsky40018472011-02-26 01:02:56 +00006520PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006521PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6522 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006523{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006524 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006525 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006526 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006527 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006528 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6529 Py_DECREF(tmp);
6530 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006531}
6532
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006533/* --- Unicode Internal Codec ------------------------------------------- */
6534
Alexander Belopolsky40018472011-02-26 01:02:56 +00006535PyObject *
6536_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006537 Py_ssize_t size,
6538 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006539{
6540 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006541 Py_ssize_t startinpos;
6542 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006543 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006544 const char *end;
6545 const char *reason;
6546 PyObject *errorHandler = NULL;
6547 PyObject *exc = NULL;
6548
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006549 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006550 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006551 1))
6552 return NULL;
6553
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006554 if (size < 0) {
6555 PyErr_BadInternalCall();
6556 return NULL;
6557 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006558 if (size == 0)
6559 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006560
Victor Stinner8f674cc2013-04-17 23:02:17 +02006561 _PyUnicodeWriter_Init(&writer);
6562 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6563 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006564 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006565 }
6566 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006567
Victor Stinner8f674cc2013-04-17 23:02:17 +02006568 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006569 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006570 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006571 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006572 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006573 endinpos = end-starts;
6574 reason = "truncated input";
6575 goto error;
6576 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006577 /* We copy the raw representation one byte at a time because the
6578 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006579 ((char *) &uch)[0] = s[0];
6580 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006581#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006582 ((char *) &uch)[2] = s[2];
6583 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006584#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006585 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006586#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006587 /* We have to sanity check the raw data, otherwise doom looms for
6588 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006589 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006590 endinpos = s - starts + Py_UNICODE_SIZE;
6591 reason = "illegal code point (> 0x10FFFF)";
6592 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006593 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006594#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006595 s += Py_UNICODE_SIZE;
6596#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006597 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006598 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006599 Py_UNICODE uch2;
6600 ((char *) &uch2)[0] = s[0];
6601 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006602 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006603 {
Victor Stinner551ac952011-11-29 22:58:13 +01006604 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006605 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006606 }
6607 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006608#endif
6609
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006610 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006611 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006612 continue;
6613
6614 error:
6615 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006616 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006617 errors, &errorHandler,
6618 "unicode_internal", reason,
6619 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006620 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006621 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006622 }
6623
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006624 Py_XDECREF(errorHandler);
6625 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006626 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006627
Benjamin Peterson29060642009-01-31 22:14:21 +00006628 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006629 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006630 Py_XDECREF(errorHandler);
6631 Py_XDECREF(exc);
6632 return NULL;
6633}
6634
Guido van Rossumd57fd912000-03-10 22:53:23 +00006635/* --- Latin-1 Codec ------------------------------------------------------ */
6636
Alexander Belopolsky40018472011-02-26 01:02:56 +00006637PyObject *
6638PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006639 Py_ssize_t size,
6640 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006641{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006643 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006644}
6645
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006646/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006647static void
6648make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006649 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006650 PyObject *unicode,
6651 Py_ssize_t startpos, Py_ssize_t endpos,
6652 const char *reason)
6653{
6654 if (*exceptionObject == NULL) {
6655 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006656 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006657 encoding, unicode, startpos, endpos, reason);
6658 }
6659 else {
6660 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6661 goto onError;
6662 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6663 goto onError;
6664 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6665 goto onError;
6666 return;
6667 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006668 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006669 }
6670}
6671
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006672/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006673static void
6674raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006675 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006676 PyObject *unicode,
6677 Py_ssize_t startpos, Py_ssize_t endpos,
6678 const char *reason)
6679{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006680 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006681 encoding, unicode, startpos, endpos, reason);
6682 if (*exceptionObject != NULL)
6683 PyCodec_StrictErrors(*exceptionObject);
6684}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006685
6686/* error handling callback helper:
6687 build arguments, call the callback and check the arguments,
6688 put the result into newpos and return the replacement string, which
6689 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006690static PyObject *
6691unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006692 PyObject **errorHandler,
6693 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006694 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006695 Py_ssize_t startpos, Py_ssize_t endpos,
6696 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006697{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006698 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006699 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006700 PyObject *restuple;
6701 PyObject *resunicode;
6702
6703 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006704 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006705 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006706 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006707 }
6708
Benjamin Petersonbac79492012-01-14 13:34:47 -05006709 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006710 return NULL;
6711 len = PyUnicode_GET_LENGTH(unicode);
6712
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006713 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006714 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006715 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006717
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006718 restuple = PyObject_CallFunctionObjArgs(
6719 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006720 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006721 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006722 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006723 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006724 Py_DECREF(restuple);
6725 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006726 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006727 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 &resunicode, newpos)) {
6729 Py_DECREF(restuple);
6730 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006731 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006732 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6733 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6734 Py_DECREF(restuple);
6735 return NULL;
6736 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006737 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006738 *newpos = len + *newpos;
6739 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006740 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006741 Py_DECREF(restuple);
6742 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006743 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006744 Py_INCREF(resunicode);
6745 Py_DECREF(restuple);
6746 return resunicode;
6747}
6748
Alexander Belopolsky40018472011-02-26 01:02:56 +00006749static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006750unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006751 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006752 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006753{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006754 /* input state */
6755 Py_ssize_t pos=0, size;
6756 int kind;
6757 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006758 /* pointer into the output */
6759 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006760 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6761 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006762 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006763 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006764 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006765 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006766 /* output object */
6767 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006768
Benjamin Petersonbac79492012-01-14 13:34:47 -05006769 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006770 return NULL;
6771 size = PyUnicode_GET_LENGTH(unicode);
6772 kind = PyUnicode_KIND(unicode);
6773 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006774 /* allocate enough for a simple encoding without
6775 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006776 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006777 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006778
6779 _PyBytesWriter_Init(&writer);
6780 str = _PyBytesWriter_Alloc(&writer, size);
6781 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006782 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006783
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006785 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006786
Benjamin Peterson29060642009-01-31 22:14:21 +00006787 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006788 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006789 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006790 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006791 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006792 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006793 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006794 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006795 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006796 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006797 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006798 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006799
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006800 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006801 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006802
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006803 /* Only overallocate the buffer if it's not the last write */
6804 writer.overallocate = (collend < size);
6805
Benjamin Peterson29060642009-01-31 22:14:21 +00006806 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006807 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006808 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02006809
6810 switch (error_handler) {
6811 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006812 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006813 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006814
6815 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006816 memset(str, '?', collend - collstart);
6817 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006818 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006819 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006820 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006821 break;
Victor Stinner50149202015-09-22 00:26:54 +02006822
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006823 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006824 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006825 writer.min_size -= (collend - collstart);
6826 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006827 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006828 if (str == NULL)
6829 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006830 pos = collend;
6831 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006832
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006833 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006834 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006835 writer.min_size -= (collend - collstart);
6836 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006837 unicode, collstart, collend);
6838 if (str == NULL)
6839 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006840 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006841 break;
Victor Stinner50149202015-09-22 00:26:54 +02006842
Victor Stinnerc3713e92015-09-29 12:32:13 +02006843 case _Py_ERROR_SURROGATEESCAPE:
6844 for (i = collstart; i < collend; ++i) {
6845 ch = PyUnicode_READ(kind, data, i);
6846 if (ch < 0xdc80 || 0xdcff < ch) {
6847 /* Not a UTF-8b surrogate */
6848 break;
6849 }
6850 *str++ = (char)(ch - 0xdc00);
6851 ++pos;
6852 }
6853 if (i >= collend)
6854 break;
6855 collstart = pos;
6856 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006857 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006858
Benjamin Peterson29060642009-01-31 22:14:21 +00006859 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006860 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6861 encoding, reason, unicode, &exc,
6862 collstart, collend, &newpos);
6863 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006864 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006865
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006866 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006867 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006868
Victor Stinner6bd525b2015-10-09 13:10:05 +02006869 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006870 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006871 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006872 PyBytes_AS_STRING(rep),
6873 PyBytes_GET_SIZE(rep));
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006874 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006875 else {
6876 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006877
Victor Stinner6bd525b2015-10-09 13:10:05 +02006878 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006880
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006881 if (limit == 256 ?
6882 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6883 !PyUnicode_IS_ASCII(rep))
6884 {
6885 /* Not all characters are smaller than limit */
6886 raise_encode_exception(&exc, encoding, unicode,
6887 collstart, collend, reason);
6888 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006889 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006890 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6891 str = _PyBytesWriter_WriteBytes(&writer, str,
6892 PyUnicode_DATA(rep),
6893 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006894 }
Alexey Izbyshev74a307d2018-08-19 21:52:04 +03006895 if (str == NULL)
6896 goto onError;
6897
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006898 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006899 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006900 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006901
6902 /* If overallocation was disabled, ensure that it was the last
6903 write. Otherwise, we missed an optimization */
6904 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006905 }
6906 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006907
Victor Stinner50149202015-09-22 00:26:54 +02006908 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006909 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006910 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006911
6912 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006913 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006914 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006915 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006916 Py_XDECREF(exc);
6917 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006918}
6919
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006920/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006921PyObject *
6922PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006923 Py_ssize_t size,
6924 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006925{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006926 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006927 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006928 if (unicode == NULL)
6929 return NULL;
6930 result = unicode_encode_ucs1(unicode, errors, 256);
6931 Py_DECREF(unicode);
6932 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006933}
6934
Alexander Belopolsky40018472011-02-26 01:02:56 +00006935PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006936_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006937{
6938 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006939 PyErr_BadArgument();
6940 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006941 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006942 if (PyUnicode_READY(unicode) == -1)
6943 return NULL;
6944 /* Fast path: if it is a one-byte string, construct
6945 bytes object directly. */
6946 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6947 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6948 PyUnicode_GET_LENGTH(unicode));
6949 /* Non-Latin-1 characters present. Defer to above function to
6950 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006951 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006952}
6953
6954PyObject*
6955PyUnicode_AsLatin1String(PyObject *unicode)
6956{
6957 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006958}
6959
6960/* --- 7-bit ASCII Codec -------------------------------------------------- */
6961
Alexander Belopolsky40018472011-02-26 01:02:56 +00006962PyObject *
6963PyUnicode_DecodeASCII(const char *s,
6964 Py_ssize_t size,
6965 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006966{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006967 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006968 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006969 int kind;
6970 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006971 Py_ssize_t startinpos;
6972 Py_ssize_t endinpos;
6973 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006974 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006975 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006976 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006977 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006978
Guido van Rossumd57fd912000-03-10 22:53:23 +00006979 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006980 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006981
Guido van Rossumd57fd912000-03-10 22:53:23 +00006982 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006983 if (size == 1 && (unsigned char)s[0] < 128)
6984 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006985
Victor Stinner8f674cc2013-04-17 23:02:17 +02006986 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006987 writer.min_length = size;
6988 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006989 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006990
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006991 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006992 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006993 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006994 writer.pos = outpos;
6995 if (writer.pos == size)
6996 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006997
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006998 s += writer.pos;
6999 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007000 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007001 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007002 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007003 PyUnicode_WRITE(kind, data, writer.pos, c);
7004 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007005 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007006 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007007 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007008
7009 /* byte outsize range 0x00..0x7f: call the error handler */
7010
7011 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02007012 error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007013
7014 switch (error_handler)
7015 {
7016 case _Py_ERROR_REPLACE:
7017 case _Py_ERROR_SURROGATEESCAPE:
7018 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007019 but we may switch to UCS2 at the first write */
7020 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7021 goto onError;
7022 kind = writer.kind;
7023 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007024
7025 if (error_handler == _Py_ERROR_REPLACE)
7026 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7027 else
7028 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7029 writer.pos++;
7030 ++s;
7031 break;
7032
7033 case _Py_ERROR_IGNORE:
7034 ++s;
7035 break;
7036
7037 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007038 startinpos = s-starts;
7039 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007040 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007041 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007042 "ascii", "ordinal not in range(128)",
7043 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007044 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007045 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007046 kind = writer.kind;
7047 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007048 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007049 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007050 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007051 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007052 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007053
Benjamin Peterson29060642009-01-31 22:14:21 +00007054 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007055 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007056 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007057 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007058 return NULL;
7059}
7060
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007061/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007062PyObject *
7063PyUnicode_EncodeASCII(const Py_UNICODE *p,
7064 Py_ssize_t size,
7065 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007066{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007067 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007068 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007069 if (unicode == NULL)
7070 return NULL;
7071 result = unicode_encode_ucs1(unicode, errors, 128);
7072 Py_DECREF(unicode);
7073 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007074}
7075
Alexander Belopolsky40018472011-02-26 01:02:56 +00007076PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007077_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007078{
7079 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007080 PyErr_BadArgument();
7081 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007082 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007083 if (PyUnicode_READY(unicode) == -1)
7084 return NULL;
7085 /* Fast path: if it is an ASCII-only string, construct bytes object
7086 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007087 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007088 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7089 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007090 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007091}
7092
7093PyObject *
7094PyUnicode_AsASCIIString(PyObject *unicode)
7095{
7096 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007097}
7098
Steve Dowercc16be82016-09-08 10:35:16 -07007099#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007100
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007101/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007102
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007103#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007104#define NEED_RETRY
7105#endif
7106
Victor Stinner3a50e702011-10-18 21:21:00 +02007107#ifndef WC_ERR_INVALID_CHARS
7108# define WC_ERR_INVALID_CHARS 0x0080
7109#endif
7110
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007111static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007112code_page_name(UINT code_page, PyObject **obj)
7113{
7114 *obj = NULL;
7115 if (code_page == CP_ACP)
7116 return "mbcs";
7117 if (code_page == CP_UTF7)
7118 return "CP_UTF7";
7119 if (code_page == CP_UTF8)
7120 return "CP_UTF8";
7121
7122 *obj = PyBytes_FromFormat("cp%u", code_page);
7123 if (*obj == NULL)
7124 return NULL;
7125 return PyBytes_AS_STRING(*obj);
7126}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007127
Victor Stinner3a50e702011-10-18 21:21:00 +02007128static DWORD
7129decode_code_page_flags(UINT code_page)
7130{
7131 if (code_page == CP_UTF7) {
7132 /* The CP_UTF7 decoder only supports flags=0 */
7133 return 0;
7134 }
7135 else
7136 return MB_ERR_INVALID_CHARS;
7137}
7138
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007139/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007140 * Decode a byte string from a Windows code page into unicode object in strict
7141 * mode.
7142 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007143 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7144 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007145 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007146static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007147decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007148 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007149 const char *in,
7150 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007151{
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007153 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007154 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007155
7156 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007157 assert(insize > 0);
7158 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7159 if (outsize <= 0)
7160 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007161
7162 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007163 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007164 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007165 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007166 if (*v == NULL)
7167 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007169 }
7170 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007171 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007172 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007173 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007174 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007176 }
7177
7178 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007179 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7180 if (outsize <= 0)
7181 goto error;
7182 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007183
Victor Stinner3a50e702011-10-18 21:21:00 +02007184error:
7185 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7186 return -2;
7187 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007188 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007189}
7190
Victor Stinner3a50e702011-10-18 21:21:00 +02007191/*
7192 * Decode a byte string from a code page into unicode object with an error
7193 * handler.
7194 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007195 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007196 * UnicodeDecodeError exception and returns -1 on error.
7197 */
7198static int
7199decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007200 PyObject **v,
7201 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007202 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007203{
7204 const char *startin = in;
7205 const char *endin = in + size;
7206 const DWORD flags = decode_code_page_flags(code_page);
7207 /* Ideally, we should get reason from FormatMessage. This is the Windows
7208 2000 English version of the message. */
7209 const char *reason = "No mapping for the Unicode character exists "
7210 "in the target code page.";
7211 /* each step cannot decode more than 1 character, but a character can be
7212 represented as a surrogate pair */
7213 wchar_t buffer[2], *startout, *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007214 int insize;
7215 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007216 PyObject *errorHandler = NULL;
7217 PyObject *exc = NULL;
7218 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007219 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 DWORD err;
7221 int ret = -1;
7222
7223 assert(size > 0);
7224
7225 encoding = code_page_name(code_page, &encoding_obj);
7226 if (encoding == NULL)
7227 return -1;
7228
Victor Stinner7d00cc12014-03-17 23:08:06 +01007229 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007230 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7231 UnicodeDecodeError. */
7232 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7233 if (exc != NULL) {
7234 PyCodec_StrictErrors(exc);
7235 Py_CLEAR(exc);
7236 }
7237 goto error;
7238 }
7239
7240 if (*v == NULL) {
7241 /* Create unicode object */
7242 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7243 PyErr_NoMemory();
7244 goto error;
7245 }
Victor Stinnerab595942011-12-17 04:59:06 +01007246 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007247 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007248 if (*v == NULL)
7249 goto error;
7250 startout = PyUnicode_AS_UNICODE(*v);
7251 }
7252 else {
7253 /* Extend unicode object */
7254 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7255 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7256 PyErr_NoMemory();
7257 goto error;
7258 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007259 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007260 goto error;
7261 startout = PyUnicode_AS_UNICODE(*v) + n;
7262 }
7263
7264 /* Decode the byte string character per character */
7265 out = startout;
7266 while (in < endin)
7267 {
7268 /* Decode a character */
7269 insize = 1;
7270 do
7271 {
7272 outsize = MultiByteToWideChar(code_page, flags,
7273 in, insize,
7274 buffer, Py_ARRAY_LENGTH(buffer));
7275 if (outsize > 0)
7276 break;
7277 err = GetLastError();
7278 if (err != ERROR_NO_UNICODE_TRANSLATION
7279 && err != ERROR_INSUFFICIENT_BUFFER)
7280 {
7281 PyErr_SetFromWindowsErr(0);
7282 goto error;
7283 }
7284 insize++;
7285 }
7286 /* 4=maximum length of a UTF-8 sequence */
7287 while (insize <= 4 && (in + insize) <= endin);
7288
7289 if (outsize <= 0) {
7290 Py_ssize_t startinpos, endinpos, outpos;
7291
Victor Stinner7d00cc12014-03-17 23:08:06 +01007292 /* last character in partial decode? */
7293 if (in + insize >= endin && !final)
7294 break;
7295
Victor Stinner3a50e702011-10-18 21:21:00 +02007296 startinpos = in - startin;
7297 endinpos = startinpos + 1;
7298 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007299 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007300 errors, &errorHandler,
7301 encoding, reason,
7302 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007303 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 {
7305 goto error;
7306 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007307 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007308 }
7309 else {
7310 in += insize;
7311 memcpy(out, buffer, outsize * sizeof(wchar_t));
7312 out += outsize;
7313 }
7314 }
7315
7316 /* write a NUL character at the end */
7317 *out = 0;
7318
7319 /* Extend unicode object */
7320 outsize = out - startout;
7321 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007322 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007323 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007324 /* (in - startin) <= size and size is an int */
7325 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007326
7327error:
7328 Py_XDECREF(encoding_obj);
7329 Py_XDECREF(errorHandler);
7330 Py_XDECREF(exc);
7331 return ret;
7332}
7333
Victor Stinner3a50e702011-10-18 21:21:00 +02007334static PyObject *
7335decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007336 const char *s, Py_ssize_t size,
7337 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007338{
Victor Stinner76a31a62011-11-04 00:05:13 +01007339 PyObject *v = NULL;
7340 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007341
Victor Stinner3a50e702011-10-18 21:21:00 +02007342 if (code_page < 0) {
7343 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7344 return NULL;
7345 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007346 if (size < 0) {
7347 PyErr_BadInternalCall();
7348 return NULL;
7349 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007350
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007351 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007352 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007353
Victor Stinner76a31a62011-11-04 00:05:13 +01007354 do
7355 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007356#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007357 if (size > INT_MAX) {
7358 chunk_size = INT_MAX;
7359 final = 0;
7360 done = 0;
7361 }
7362 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007363#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007364 {
7365 chunk_size = (int)size;
7366 final = (consumed == NULL);
7367 done = 1;
7368 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007369
Victor Stinner76a31a62011-11-04 00:05:13 +01007370 if (chunk_size == 0 && done) {
7371 if (v != NULL)
7372 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007373 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007374 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007375
Victor Stinner76a31a62011-11-04 00:05:13 +01007376 converted = decode_code_page_strict(code_page, &v,
7377 s, chunk_size);
7378 if (converted == -2)
7379 converted = decode_code_page_errors(code_page, &v,
7380 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007381 errors, final);
7382 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007383
7384 if (converted < 0) {
7385 Py_XDECREF(v);
7386 return NULL;
7387 }
7388
7389 if (consumed)
7390 *consumed += converted;
7391
7392 s += converted;
7393 size -= converted;
7394 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007395
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007396 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007397}
7398
Alexander Belopolsky40018472011-02-26 01:02:56 +00007399PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007400PyUnicode_DecodeCodePageStateful(int code_page,
7401 const char *s,
7402 Py_ssize_t size,
7403 const char *errors,
7404 Py_ssize_t *consumed)
7405{
7406 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7407}
7408
7409PyObject *
7410PyUnicode_DecodeMBCSStateful(const char *s,
7411 Py_ssize_t size,
7412 const char *errors,
7413 Py_ssize_t *consumed)
7414{
7415 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7416}
7417
7418PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007419PyUnicode_DecodeMBCS(const char *s,
7420 Py_ssize_t size,
7421 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007422{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007423 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7424}
7425
Victor Stinner3a50e702011-10-18 21:21:00 +02007426static DWORD
7427encode_code_page_flags(UINT code_page, const char *errors)
7428{
7429 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007430 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007431 }
7432 else if (code_page == CP_UTF7) {
7433 /* CP_UTF7 only supports flags=0 */
7434 return 0;
7435 }
7436 else {
7437 if (errors != NULL && strcmp(errors, "replace") == 0)
7438 return 0;
7439 else
7440 return WC_NO_BEST_FIT_CHARS;
7441 }
7442}
7443
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007444/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007445 * Encode a Unicode string to a Windows code page into a byte string in strict
7446 * mode.
7447 *
7448 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007449 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007450 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007451static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007452encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007453 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007454 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007455{
Victor Stinner554f3f02010-06-16 23:33:54 +00007456 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007457 BOOL *pusedDefaultChar = &usedDefaultChar;
7458 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007459 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007460 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007461 const DWORD flags = encode_code_page_flags(code_page, NULL);
7462 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007463 /* Create a substring so that we can get the UTF-16 representation
7464 of just the slice under consideration. */
7465 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007466
Martin v. Löwis3d325192011-11-04 18:23:06 +01007467 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007468
Victor Stinner3a50e702011-10-18 21:21:00 +02007469 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007470 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007471 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007472 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007473
Victor Stinner2fc507f2011-11-04 20:06:39 +01007474 substring = PyUnicode_Substring(unicode, offset, offset+len);
7475 if (substring == NULL)
7476 return -1;
7477 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7478 if (p == NULL) {
7479 Py_DECREF(substring);
7480 return -1;
7481 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007482 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007483
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007484 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007485 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007486 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007487 NULL, 0,
7488 NULL, pusedDefaultChar);
7489 if (outsize <= 0)
7490 goto error;
7491 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007492 if (pusedDefaultChar && *pusedDefaultChar) {
7493 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007494 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007495 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007496
Victor Stinner3a50e702011-10-18 21:21:00 +02007497 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007498 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007499 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007500 if (*outbytes == NULL) {
7501 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007502 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007503 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007504 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007505 }
7506 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007507 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007508 const Py_ssize_t n = PyBytes_Size(*outbytes);
7509 if (outsize > PY_SSIZE_T_MAX - n) {
7510 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007511 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007512 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007513 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007514 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7515 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007516 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007517 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007518 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007519 }
7520
7521 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007522 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007523 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007524 out, outsize,
7525 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007526 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007527 if (outsize <= 0)
7528 goto error;
7529 if (pusedDefaultChar && *pusedDefaultChar)
7530 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007531 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007532
Victor Stinner3a50e702011-10-18 21:21:00 +02007533error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007534 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007535 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7536 return -2;
7537 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007538 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007539}
7540
Victor Stinner3a50e702011-10-18 21:21:00 +02007541/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007542 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007543 * error handler.
7544 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007545 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007546 * -1 on other error.
7547 */
7548static int
7549encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007550 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007551 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007552{
Victor Stinner3a50e702011-10-18 21:21:00 +02007553 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007554 Py_ssize_t pos = unicode_offset;
7555 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007556 /* Ideally, we should get reason from FormatMessage. This is the Windows
7557 2000 English version of the message. */
7558 const char *reason = "invalid character";
7559 /* 4=maximum length of a UTF-8 sequence */
7560 char buffer[4];
7561 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7562 Py_ssize_t outsize;
7563 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007564 PyObject *errorHandler = NULL;
7565 PyObject *exc = NULL;
7566 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007567 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007568 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007569 PyObject *rep;
7570 int ret = -1;
7571
7572 assert(insize > 0);
7573
7574 encoding = code_page_name(code_page, &encoding_obj);
7575 if (encoding == NULL)
7576 return -1;
7577
7578 if (errors == NULL || strcmp(errors, "strict") == 0) {
7579 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7580 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007581 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007582 if (exc != NULL) {
7583 PyCodec_StrictErrors(exc);
7584 Py_DECREF(exc);
7585 }
7586 Py_XDECREF(encoding_obj);
7587 return -1;
7588 }
7589
7590 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7591 pusedDefaultChar = &usedDefaultChar;
7592 else
7593 pusedDefaultChar = NULL;
7594
7595 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7596 PyErr_NoMemory();
7597 goto error;
7598 }
7599 outsize = insize * Py_ARRAY_LENGTH(buffer);
7600
7601 if (*outbytes == NULL) {
7602 /* Create string object */
7603 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7604 if (*outbytes == NULL)
7605 goto error;
7606 out = PyBytes_AS_STRING(*outbytes);
7607 }
7608 else {
7609 /* Extend string object */
7610 Py_ssize_t n = PyBytes_Size(*outbytes);
7611 if (n > PY_SSIZE_T_MAX - outsize) {
7612 PyErr_NoMemory();
7613 goto error;
7614 }
7615 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7616 goto error;
7617 out = PyBytes_AS_STRING(*outbytes) + n;
7618 }
7619
7620 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007621 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007622 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007623 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7624 wchar_t chars[2];
7625 int charsize;
7626 if (ch < 0x10000) {
7627 chars[0] = (wchar_t)ch;
7628 charsize = 1;
7629 }
7630 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007631 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7632 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007633 charsize = 2;
7634 }
7635
Victor Stinner3a50e702011-10-18 21:21:00 +02007636 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007637 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007638 buffer, Py_ARRAY_LENGTH(buffer),
7639 NULL, pusedDefaultChar);
7640 if (outsize > 0) {
7641 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7642 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007643 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007644 memcpy(out, buffer, outsize);
7645 out += outsize;
7646 continue;
7647 }
7648 }
7649 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7650 PyErr_SetFromWindowsErr(0);
7651 goto error;
7652 }
7653
Victor Stinner3a50e702011-10-18 21:21:00 +02007654 rep = unicode_encode_call_errorhandler(
7655 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007656 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007657 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007658 if (rep == NULL)
7659 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007660 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007661
7662 if (PyBytes_Check(rep)) {
7663 outsize = PyBytes_GET_SIZE(rep);
7664 if (outsize != 1) {
7665 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7666 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7667 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7668 Py_DECREF(rep);
7669 goto error;
7670 }
7671 out = PyBytes_AS_STRING(*outbytes) + offset;
7672 }
7673 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7674 out += outsize;
7675 }
7676 else {
7677 Py_ssize_t i;
7678 enum PyUnicode_Kind kind;
7679 void *data;
7680
Benjamin Petersonbac79492012-01-14 13:34:47 -05007681 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007682 Py_DECREF(rep);
7683 goto error;
7684 }
7685
7686 outsize = PyUnicode_GET_LENGTH(rep);
7687 if (outsize != 1) {
7688 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7689 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7690 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7691 Py_DECREF(rep);
7692 goto error;
7693 }
7694 out = PyBytes_AS_STRING(*outbytes) + offset;
7695 }
7696 kind = PyUnicode_KIND(rep);
7697 data = PyUnicode_DATA(rep);
7698 for (i=0; i < outsize; i++) {
7699 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7700 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007701 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007702 encoding, unicode,
7703 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007704 "unable to encode error handler result to ASCII");
7705 Py_DECREF(rep);
7706 goto error;
7707 }
7708 *out = (unsigned char)ch;
7709 out++;
7710 }
7711 }
7712 Py_DECREF(rep);
7713 }
7714 /* write a NUL byte */
7715 *out = 0;
7716 outsize = out - PyBytes_AS_STRING(*outbytes);
7717 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7718 if (_PyBytes_Resize(outbytes, outsize) < 0)
7719 goto error;
7720 ret = 0;
7721
7722error:
7723 Py_XDECREF(encoding_obj);
7724 Py_XDECREF(errorHandler);
7725 Py_XDECREF(exc);
7726 return ret;
7727}
7728
Victor Stinner3a50e702011-10-18 21:21:00 +02007729static PyObject *
7730encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007731 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007732 const char *errors)
7733{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007734 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007735 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007736 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007737 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007738
Victor Stinner29dacf22015-01-26 16:41:32 +01007739 if (!PyUnicode_Check(unicode)) {
7740 PyErr_BadArgument();
7741 return NULL;
7742 }
7743
Benjamin Petersonbac79492012-01-14 13:34:47 -05007744 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007745 return NULL;
7746 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007747
Victor Stinner3a50e702011-10-18 21:21:00 +02007748 if (code_page < 0) {
7749 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7750 return NULL;
7751 }
7752
Martin v. Löwis3d325192011-11-04 18:23:06 +01007753 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007754 return PyBytes_FromStringAndSize(NULL, 0);
7755
Victor Stinner7581cef2011-11-03 22:32:33 +01007756 offset = 0;
7757 do
7758 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007759#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007760 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007761 chunks. */
7762 if (len > INT_MAX/2) {
7763 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007764 done = 0;
7765 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007766 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007767#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007768 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007769 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007770 done = 1;
7771 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007772
Victor Stinner76a31a62011-11-04 00:05:13 +01007773 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007774 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007775 errors);
7776 if (ret == -2)
7777 ret = encode_code_page_errors(code_page, &outbytes,
7778 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007779 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007780 if (ret < 0) {
7781 Py_XDECREF(outbytes);
7782 return NULL;
7783 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007784
Victor Stinner7581cef2011-11-03 22:32:33 +01007785 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007786 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007787 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007788
Victor Stinner3a50e702011-10-18 21:21:00 +02007789 return outbytes;
7790}
7791
7792PyObject *
7793PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7794 Py_ssize_t size,
7795 const char *errors)
7796{
Victor Stinner7581cef2011-11-03 22:32:33 +01007797 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007798 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007799 if (unicode == NULL)
7800 return NULL;
7801 res = encode_code_page(CP_ACP, unicode, errors);
7802 Py_DECREF(unicode);
7803 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007804}
7805
7806PyObject *
7807PyUnicode_EncodeCodePage(int code_page,
7808 PyObject *unicode,
7809 const char *errors)
7810{
Victor Stinner7581cef2011-11-03 22:32:33 +01007811 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007812}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007813
Alexander Belopolsky40018472011-02-26 01:02:56 +00007814PyObject *
7815PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007816{
Victor Stinner7581cef2011-11-03 22:32:33 +01007817 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007818}
7819
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007820#undef NEED_RETRY
7821
Steve Dowercc16be82016-09-08 10:35:16 -07007822#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007823
Guido van Rossumd57fd912000-03-10 22:53:23 +00007824/* --- Character Mapping Codec -------------------------------------------- */
7825
Victor Stinnerfb161b12013-04-18 01:44:27 +02007826static int
7827charmap_decode_string(const char *s,
7828 Py_ssize_t size,
7829 PyObject *mapping,
7830 const char *errors,
7831 _PyUnicodeWriter *writer)
7832{
7833 const char *starts = s;
7834 const char *e;
7835 Py_ssize_t startinpos, endinpos;
7836 PyObject *errorHandler = NULL, *exc = NULL;
7837 Py_ssize_t maplen;
7838 enum PyUnicode_Kind mapkind;
7839 void *mapdata;
7840 Py_UCS4 x;
7841 unsigned char ch;
7842
7843 if (PyUnicode_READY(mapping) == -1)
7844 return -1;
7845
7846 maplen = PyUnicode_GET_LENGTH(mapping);
7847 mapdata = PyUnicode_DATA(mapping);
7848 mapkind = PyUnicode_KIND(mapping);
7849
7850 e = s + size;
7851
7852 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7853 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7854 * is disabled in encoding aliases, latin1 is preferred because
7855 * its implementation is faster. */
7856 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7857 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7858 Py_UCS4 maxchar = writer->maxchar;
7859
7860 assert (writer->kind == PyUnicode_1BYTE_KIND);
7861 while (s < e) {
7862 ch = *s;
7863 x = mapdata_ucs1[ch];
7864 if (x > maxchar) {
7865 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7866 goto onError;
7867 maxchar = writer->maxchar;
7868 outdata = (Py_UCS1 *)writer->data;
7869 }
7870 outdata[writer->pos] = x;
7871 writer->pos++;
7872 ++s;
7873 }
7874 return 0;
7875 }
7876
7877 while (s < e) {
7878 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7879 enum PyUnicode_Kind outkind = writer->kind;
7880 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7881 if (outkind == PyUnicode_1BYTE_KIND) {
7882 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7883 Py_UCS4 maxchar = writer->maxchar;
7884 while (s < e) {
7885 ch = *s;
7886 x = mapdata_ucs2[ch];
7887 if (x > maxchar)
7888 goto Error;
7889 outdata[writer->pos] = x;
7890 writer->pos++;
7891 ++s;
7892 }
7893 break;
7894 }
7895 else if (outkind == PyUnicode_2BYTE_KIND) {
7896 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7897 while (s < e) {
7898 ch = *s;
7899 x = mapdata_ucs2[ch];
7900 if (x == 0xFFFE)
7901 goto Error;
7902 outdata[writer->pos] = x;
7903 writer->pos++;
7904 ++s;
7905 }
7906 break;
7907 }
7908 }
7909 ch = *s;
7910
7911 if (ch < maplen)
7912 x = PyUnicode_READ(mapkind, mapdata, ch);
7913 else
7914 x = 0xfffe; /* invalid value */
7915Error:
7916 if (x == 0xfffe)
7917 {
7918 /* undefined mapping */
7919 startinpos = s-starts;
7920 endinpos = startinpos+1;
7921 if (unicode_decode_call_errorhandler_writer(
7922 errors, &errorHandler,
7923 "charmap", "character maps to <undefined>",
7924 &starts, &e, &startinpos, &endinpos, &exc, &s,
7925 writer)) {
7926 goto onError;
7927 }
7928 continue;
7929 }
7930
7931 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7932 goto onError;
7933 ++s;
7934 }
7935 Py_XDECREF(errorHandler);
7936 Py_XDECREF(exc);
7937 return 0;
7938
7939onError:
7940 Py_XDECREF(errorHandler);
7941 Py_XDECREF(exc);
7942 return -1;
7943}
7944
7945static int
7946charmap_decode_mapping(const char *s,
7947 Py_ssize_t size,
7948 PyObject *mapping,
7949 const char *errors,
7950 _PyUnicodeWriter *writer)
7951{
7952 const char *starts = s;
7953 const char *e;
7954 Py_ssize_t startinpos, endinpos;
7955 PyObject *errorHandler = NULL, *exc = NULL;
7956 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007957 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007958
7959 e = s + size;
7960
7961 while (s < e) {
7962 ch = *s;
7963
7964 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7965 key = PyLong_FromLong((long)ch);
7966 if (key == NULL)
7967 goto onError;
7968
7969 item = PyObject_GetItem(mapping, key);
7970 Py_DECREF(key);
7971 if (item == NULL) {
7972 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7973 /* No mapping found means: mapping is undefined. */
7974 PyErr_Clear();
7975 goto Undefined;
7976 } else
7977 goto onError;
7978 }
7979
7980 /* Apply mapping */
7981 if (item == Py_None)
7982 goto Undefined;
7983 if (PyLong_Check(item)) {
7984 long value = PyLong_AS_LONG(item);
7985 if (value == 0xFFFE)
7986 goto Undefined;
7987 if (value < 0 || value > MAX_UNICODE) {
7988 PyErr_Format(PyExc_TypeError,
7989 "character mapping must be in range(0x%lx)",
7990 (unsigned long)MAX_UNICODE + 1);
7991 goto onError;
7992 }
7993
7994 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7995 goto onError;
7996 }
7997 else if (PyUnicode_Check(item)) {
7998 if (PyUnicode_READY(item) == -1)
7999 goto onError;
8000 if (PyUnicode_GET_LENGTH(item) == 1) {
8001 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8002 if (value == 0xFFFE)
8003 goto Undefined;
8004 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8005 goto onError;
8006 }
8007 else {
8008 writer->overallocate = 1;
8009 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8010 goto onError;
8011 }
8012 }
8013 else {
8014 /* wrong return value */
8015 PyErr_SetString(PyExc_TypeError,
8016 "character mapping must return integer, None or str");
8017 goto onError;
8018 }
8019 Py_CLEAR(item);
8020 ++s;
8021 continue;
8022
8023Undefined:
8024 /* undefined mapping */
8025 Py_CLEAR(item);
8026 startinpos = s-starts;
8027 endinpos = startinpos+1;
8028 if (unicode_decode_call_errorhandler_writer(
8029 errors, &errorHandler,
8030 "charmap", "character maps to <undefined>",
8031 &starts, &e, &startinpos, &endinpos, &exc, &s,
8032 writer)) {
8033 goto onError;
8034 }
8035 }
8036 Py_XDECREF(errorHandler);
8037 Py_XDECREF(exc);
8038 return 0;
8039
8040onError:
8041 Py_XDECREF(item);
8042 Py_XDECREF(errorHandler);
8043 Py_XDECREF(exc);
8044 return -1;
8045}
8046
Alexander Belopolsky40018472011-02-26 01:02:56 +00008047PyObject *
8048PyUnicode_DecodeCharmap(const char *s,
8049 Py_ssize_t size,
8050 PyObject *mapping,
8051 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008052{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008053 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008054
Guido van Rossumd57fd912000-03-10 22:53:23 +00008055 /* Default to Latin-1 */
8056 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008057 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008058
Guido van Rossumd57fd912000-03-10 22:53:23 +00008059 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008060 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008061 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008062 writer.min_length = size;
8063 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008064 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008065
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008066 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008067 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8068 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008069 }
8070 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008071 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8072 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008073 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008074 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008075
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008077 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008078 return NULL;
8079}
8080
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008081/* Charmap encoding: the lookup table */
8082
Alexander Belopolsky40018472011-02-26 01:02:56 +00008083struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008084 PyObject_HEAD
8085 unsigned char level1[32];
8086 int count2, count3;
8087 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088};
8089
8090static PyObject*
8091encoding_map_size(PyObject *obj, PyObject* args)
8092{
8093 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008094 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008096}
8097
8098static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008099 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008100 PyDoc_STR("Return the size (in bytes) of this object") },
8101 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102};
8103
8104static void
8105encoding_map_dealloc(PyObject* o)
8106{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008107 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108}
8109
8110static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008111 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 "EncodingMap", /*tp_name*/
8113 sizeof(struct encoding_map), /*tp_basicsize*/
8114 0, /*tp_itemsize*/
8115 /* methods */
8116 encoding_map_dealloc, /*tp_dealloc*/
8117 0, /*tp_print*/
8118 0, /*tp_getattr*/
8119 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008120 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008121 0, /*tp_repr*/
8122 0, /*tp_as_number*/
8123 0, /*tp_as_sequence*/
8124 0, /*tp_as_mapping*/
8125 0, /*tp_hash*/
8126 0, /*tp_call*/
8127 0, /*tp_str*/
8128 0, /*tp_getattro*/
8129 0, /*tp_setattro*/
8130 0, /*tp_as_buffer*/
8131 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8132 0, /*tp_doc*/
8133 0, /*tp_traverse*/
8134 0, /*tp_clear*/
8135 0, /*tp_richcompare*/
8136 0, /*tp_weaklistoffset*/
8137 0, /*tp_iter*/
8138 0, /*tp_iternext*/
8139 encoding_map_methods, /*tp_methods*/
8140 0, /*tp_members*/
8141 0, /*tp_getset*/
8142 0, /*tp_base*/
8143 0, /*tp_dict*/
8144 0, /*tp_descr_get*/
8145 0, /*tp_descr_set*/
8146 0, /*tp_dictoffset*/
8147 0, /*tp_init*/
8148 0, /*tp_alloc*/
8149 0, /*tp_new*/
8150 0, /*tp_free*/
8151 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008152};
8153
8154PyObject*
8155PyUnicode_BuildEncodingMap(PyObject* string)
8156{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008157 PyObject *result;
8158 struct encoding_map *mresult;
8159 int i;
8160 int need_dict = 0;
8161 unsigned char level1[32];
8162 unsigned char level2[512];
8163 unsigned char *mlevel1, *mlevel2, *mlevel3;
8164 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008165 int kind;
8166 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008167 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008168 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008169
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008170 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171 PyErr_BadArgument();
8172 return NULL;
8173 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008174 kind = PyUnicode_KIND(string);
8175 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008176 length = PyUnicode_GET_LENGTH(string);
8177 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008178 memset(level1, 0xFF, sizeof level1);
8179 memset(level2, 0xFF, sizeof level2);
8180
8181 /* If there isn't a one-to-one mapping of NULL to \0,
8182 or if there are non-BMP characters, we need to use
8183 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008184 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008185 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008186 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008187 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008188 ch = PyUnicode_READ(kind, data, i);
8189 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008190 need_dict = 1;
8191 break;
8192 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008193 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008194 /* unmapped character */
8195 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008196 l1 = ch >> 11;
8197 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008198 if (level1[l1] == 0xFF)
8199 level1[l1] = count2++;
8200 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008201 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008202 }
8203
8204 if (count2 >= 0xFF || count3 >= 0xFF)
8205 need_dict = 1;
8206
8207 if (need_dict) {
8208 PyObject *result = PyDict_New();
8209 PyObject *key, *value;
8210 if (!result)
8211 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008212 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008213 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008214 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008215 if (!key || !value)
8216 goto failed1;
8217 if (PyDict_SetItem(result, key, value) == -1)
8218 goto failed1;
8219 Py_DECREF(key);
8220 Py_DECREF(value);
8221 }
8222 return result;
8223 failed1:
8224 Py_XDECREF(key);
8225 Py_XDECREF(value);
8226 Py_DECREF(result);
8227 return NULL;
8228 }
8229
8230 /* Create a three-level trie */
8231 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8232 16*count2 + 128*count3 - 1);
8233 if (!result)
8234 return PyErr_NoMemory();
8235 PyObject_Init(result, &EncodingMapType);
8236 mresult = (struct encoding_map*)result;
8237 mresult->count2 = count2;
8238 mresult->count3 = count3;
8239 mlevel1 = mresult->level1;
8240 mlevel2 = mresult->level23;
8241 mlevel3 = mresult->level23 + 16*count2;
8242 memcpy(mlevel1, level1, 32);
8243 memset(mlevel2, 0xFF, 16*count2);
8244 memset(mlevel3, 0, 128*count3);
8245 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008246 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008247 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008248 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8249 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008250 /* unmapped character */
8251 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008252 o1 = ch>>11;
8253 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008254 i2 = 16*mlevel1[o1] + o2;
8255 if (mlevel2[i2] == 0xFF)
8256 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008257 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008258 i3 = 128*mlevel2[i2] + o3;
8259 mlevel3[i3] = i;
8260 }
8261 return result;
8262}
8263
8264static int
Victor Stinner22168992011-11-20 17:09:18 +01008265encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008266{
8267 struct encoding_map *map = (struct encoding_map*)mapping;
8268 int l1 = c>>11;
8269 int l2 = (c>>7) & 0xF;
8270 int l3 = c & 0x7F;
8271 int i;
8272
Victor Stinner22168992011-11-20 17:09:18 +01008273 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008274 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008275 if (c == 0)
8276 return 0;
8277 /* level 1*/
8278 i = map->level1[l1];
8279 if (i == 0xFF) {
8280 return -1;
8281 }
8282 /* level 2*/
8283 i = map->level23[16*i+l2];
8284 if (i == 0xFF) {
8285 return -1;
8286 }
8287 /* level 3 */
8288 i = map->level23[16*map->count2 + 128*i + l3];
8289 if (i == 0) {
8290 return -1;
8291 }
8292 return i;
8293}
8294
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295/* Lookup the character ch in the mapping. If the character
8296 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008297 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008298static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008299charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008300{
Christian Heimes217cfd12007-12-02 14:31:20 +00008301 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302 PyObject *x;
8303
8304 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306 x = PyObject_GetItem(mapping, w);
8307 Py_DECREF(w);
8308 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008309 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8310 /* No mapping found means: mapping is undefined. */
8311 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008312 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008313 } else
8314 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008315 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008316 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008317 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008318 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 long value = PyLong_AS_LONG(x);
8320 if (value < 0 || value > 255) {
8321 PyErr_SetString(PyExc_TypeError,
8322 "character mapping must be in range(256)");
8323 Py_DECREF(x);
8324 return NULL;
8325 }
8326 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008327 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008328 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008329 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008330 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 /* wrong return value */
8332 PyErr_Format(PyExc_TypeError,
8333 "character mapping must return integer, bytes or None, not %.400s",
8334 x->ob_type->tp_name);
8335 Py_DECREF(x);
8336 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008337 }
8338}
8339
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008340static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008341charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008342{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008343 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8344 /* exponentially overallocate to minimize reallocations */
8345 if (requiredsize < 2*outsize)
8346 requiredsize = 2*outsize;
8347 if (_PyBytes_Resize(outobj, requiredsize))
8348 return -1;
8349 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008350}
8351
Benjamin Peterson14339b62009-01-31 16:36:08 +00008352typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008353 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008354} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008356 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 space is available. Return a new reference to the object that
8358 was put in the output buffer, or Py_None, if the mapping was undefined
8359 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008360 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008361static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008362charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008363 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008365 PyObject *rep;
8366 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008367 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368
Christian Heimes90aa7642007-12-19 02:45:37 +00008369 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008370 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008372 if (res == -1)
8373 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008374 if (outsize<requiredsize)
8375 if (charmapencode_resize(outobj, outpos, requiredsize))
8376 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008377 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 outstart[(*outpos)++] = (char)res;
8379 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008380 }
8381
8382 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008384 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008385 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 Py_DECREF(rep);
8387 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008388 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 if (PyLong_Check(rep)) {
8390 Py_ssize_t requiredsize = *outpos+1;
8391 if (outsize<requiredsize)
8392 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8393 Py_DECREF(rep);
8394 return enc_EXCEPTION;
8395 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008396 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008397 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008398 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008399 else {
8400 const char *repchars = PyBytes_AS_STRING(rep);
8401 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8402 Py_ssize_t requiredsize = *outpos+repsize;
8403 if (outsize<requiredsize)
8404 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8405 Py_DECREF(rep);
8406 return enc_EXCEPTION;
8407 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008408 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 memcpy(outstart + *outpos, repchars, repsize);
8410 *outpos += repsize;
8411 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008412 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008413 Py_DECREF(rep);
8414 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415}
8416
8417/* handle an error in PyUnicode_EncodeCharmap
8418 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008419static int
8420charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008421 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008423 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008424 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425{
8426 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008427 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008428 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008429 enum PyUnicode_Kind kind;
8430 void *data;
8431 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008432 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008433 Py_ssize_t collstartpos = *inpos;
8434 Py_ssize_t collendpos = *inpos+1;
8435 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008436 const char *encoding = "charmap";
8437 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008438 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008439 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008440 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441
Benjamin Petersonbac79492012-01-14 13:34:47 -05008442 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008443 return -1;
8444 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445 /* find all unencodable characters */
8446 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008447 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008448 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008449 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008450 val = encoding_map_lookup(ch, mapping);
8451 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 break;
8453 ++collendpos;
8454 continue;
8455 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008456
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008457 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8458 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 if (rep==NULL)
8460 return -1;
8461 else if (rep!=Py_None) {
8462 Py_DECREF(rep);
8463 break;
8464 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008465 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467 }
8468 /* cache callback name lookup
8469 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008470 if (*error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02008471 *error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02008472
8473 switch (*error_handler) {
8474 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008475 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008476 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008477
8478 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008479 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008480 x = charmapencode_output('?', mapping, res, respos);
8481 if (x==enc_EXCEPTION) {
8482 return -1;
8483 }
8484 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008485 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 return -1;
8487 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008488 }
8489 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008490 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008491 *inpos = collendpos;
8492 break;
Victor Stinner50149202015-09-22 00:26:54 +02008493
8494 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008495 /* generate replacement (temporarily (mis)uses p) */
8496 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 char buffer[2+29+1+1];
8498 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008499 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 for (cp = buffer; *cp; ++cp) {
8501 x = charmapencode_output(*cp, mapping, res, respos);
8502 if (x==enc_EXCEPTION)
8503 return -1;
8504 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008505 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 return -1;
8507 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008508 }
8509 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008510 *inpos = collendpos;
8511 break;
Victor Stinner50149202015-09-22 00:26:54 +02008512
Benjamin Peterson14339b62009-01-31 16:36:08 +00008513 default:
Victor Stinner50149202015-09-22 00:26:54 +02008514 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008515 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008516 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008517 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008518 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008519 if (PyBytes_Check(repunicode)) {
8520 /* Directly copy bytes result to output. */
8521 Py_ssize_t outsize = PyBytes_Size(*res);
8522 Py_ssize_t requiredsize;
8523 repsize = PyBytes_Size(repunicode);
8524 requiredsize = *respos + repsize;
8525 if (requiredsize > outsize)
8526 /* Make room for all additional bytes. */
8527 if (charmapencode_resize(res, respos, requiredsize)) {
8528 Py_DECREF(repunicode);
8529 return -1;
8530 }
8531 memcpy(PyBytes_AsString(*res) + *respos,
8532 PyBytes_AsString(repunicode), repsize);
8533 *respos += repsize;
8534 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008535 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008536 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008537 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008538 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008539 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008540 Py_DECREF(repunicode);
8541 return -1;
8542 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008543 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008544 data = PyUnicode_DATA(repunicode);
8545 kind = PyUnicode_KIND(repunicode);
8546 for (index = 0; index < repsize; index++) {
8547 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8548 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008549 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008550 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 return -1;
8552 }
8553 else if (x==enc_FAILED) {
8554 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008555 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 return -1;
8557 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008558 }
8559 *inpos = newpos;
8560 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008561 }
8562 return 0;
8563}
8564
Alexander Belopolsky40018472011-02-26 01:02:56 +00008565PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008566_PyUnicode_EncodeCharmap(PyObject *unicode,
8567 PyObject *mapping,
8568 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008570 /* output object */
8571 PyObject *res = NULL;
8572 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008573 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008574 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008575 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008576 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008577 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008578 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008579 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008580 void *data;
8581 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008582
Benjamin Petersonbac79492012-01-14 13:34:47 -05008583 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008584 return NULL;
8585 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008586 data = PyUnicode_DATA(unicode);
8587 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008588
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589 /* Default to Latin-1 */
8590 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008591 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593 /* allocate enough for a simple encoding without
8594 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008595 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 if (res == NULL)
8597 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008598 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008600
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008601 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008602 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008603 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008604 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008605 if (x==enc_EXCEPTION) /* error */
8606 goto onError;
8607 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008608 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008610 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 &res, &respos)) {
8612 goto onError;
8613 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008614 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 else
8616 /* done with this character => adjust input position */
8617 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008618 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008619
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008620 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008621 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008622 if (_PyBytes_Resize(&res, respos) < 0)
8623 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008624
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008625 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008626 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627 return res;
8628
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008630 Py_XDECREF(res);
8631 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008632 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008633 return NULL;
8634}
8635
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008636/* Deprecated */
8637PyObject *
8638PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8639 Py_ssize_t size,
8640 PyObject *mapping,
8641 const char *errors)
8642{
8643 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008644 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008645 if (unicode == NULL)
8646 return NULL;
8647 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8648 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008649 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008650}
8651
Alexander Belopolsky40018472011-02-26 01:02:56 +00008652PyObject *
8653PyUnicode_AsCharmapString(PyObject *unicode,
8654 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008655{
8656 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 PyErr_BadArgument();
8658 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008659 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008660 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008661}
8662
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008663/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008664static void
8665make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008667 Py_ssize_t startpos, Py_ssize_t endpos,
8668 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008669{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008670 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 *exceptionObject = _PyUnicodeTranslateError_Create(
8672 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008673 }
8674 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8676 goto onError;
8677 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8678 goto onError;
8679 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8680 goto onError;
8681 return;
8682 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008683 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008684 }
8685}
8686
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008687/* error handling callback helper:
8688 build arguments, call the callback and check the arguments,
8689 put the result into newpos and return the replacement string, which
8690 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008691static PyObject *
8692unicode_translate_call_errorhandler(const char *errors,
8693 PyObject **errorHandler,
8694 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008696 Py_ssize_t startpos, Py_ssize_t endpos,
8697 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008698{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008699 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008700
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008701 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008702 PyObject *restuple;
8703 PyObject *resunicode;
8704
8705 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008707 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008708 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008709 }
8710
8711 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008713 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008715
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008716 restuple = PyObject_CallFunctionObjArgs(
8717 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008718 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008719 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008720 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008721 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 Py_DECREF(restuple);
8723 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008724 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008725 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 &resunicode, &i_newpos)) {
8727 Py_DECREF(restuple);
8728 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008729 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008730 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008731 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008732 else
8733 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008735 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008736 Py_DECREF(restuple);
8737 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008738 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008739 Py_INCREF(resunicode);
8740 Py_DECREF(restuple);
8741 return resunicode;
8742}
8743
8744/* Lookup the character ch in the mapping and put the result in result,
8745 which must be decrefed by the caller.
8746 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008747static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008748charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008749{
Christian Heimes217cfd12007-12-02 14:31:20 +00008750 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008751 PyObject *x;
8752
8753 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008755 x = PyObject_GetItem(mapping, w);
8756 Py_DECREF(w);
8757 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008758 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8759 /* No mapping found means: use 1:1 mapping. */
8760 PyErr_Clear();
8761 *result = NULL;
8762 return 0;
8763 } else
8764 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008765 }
8766 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008767 *result = x;
8768 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008769 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008770 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008771 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008772 if (value < 0 || value > MAX_UNICODE) {
8773 PyErr_Format(PyExc_ValueError,
8774 "character mapping must be in range(0x%x)",
8775 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008776 Py_DECREF(x);
8777 return -1;
8778 }
8779 *result = x;
8780 return 0;
8781 }
8782 else if (PyUnicode_Check(x)) {
8783 *result = x;
8784 return 0;
8785 }
8786 else {
8787 /* wrong return value */
8788 PyErr_SetString(PyExc_TypeError,
8789 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008790 Py_DECREF(x);
8791 return -1;
8792 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008793}
Victor Stinner1194ea02014-04-04 19:37:40 +02008794
8795/* lookup the character, write the result into the writer.
8796 Return 1 if the result was written into the writer, return 0 if the mapping
8797 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008798static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008799charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8800 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008801{
Victor Stinner1194ea02014-04-04 19:37:40 +02008802 PyObject *item;
8803
8804 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008805 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008806
8807 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008808 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008809 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008810 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008811 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008812 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008813 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008814
8815 if (item == Py_None) {
8816 Py_DECREF(item);
8817 return 0;
8818 }
8819
8820 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008821 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8822 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8823 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008824 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8825 Py_DECREF(item);
8826 return -1;
8827 }
8828 Py_DECREF(item);
8829 return 1;
8830 }
8831
8832 if (!PyUnicode_Check(item)) {
8833 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008834 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008835 }
8836
8837 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8838 Py_DECREF(item);
8839 return -1;
8840 }
8841
8842 Py_DECREF(item);
8843 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008844}
8845
Victor Stinner89a76ab2014-04-05 11:44:04 +02008846static int
8847unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8848 Py_UCS1 *translate)
8849{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008850 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008851 int ret = 0;
8852
Victor Stinner89a76ab2014-04-05 11:44:04 +02008853 if (charmaptranslate_lookup(ch, mapping, &item)) {
8854 return -1;
8855 }
8856
8857 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008858 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008859 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008860 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008861 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008862 /* not found => default to 1:1 mapping */
8863 translate[ch] = ch;
8864 return 1;
8865 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008866 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008867 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008868 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8869 used it */
8870 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008871 /* invalid character or character outside ASCII:
8872 skip the fast translate */
8873 goto exit;
8874 }
8875 translate[ch] = (Py_UCS1)replace;
8876 }
8877 else if (PyUnicode_Check(item)) {
8878 Py_UCS4 replace;
8879
8880 if (PyUnicode_READY(item) == -1) {
8881 Py_DECREF(item);
8882 return -1;
8883 }
8884 if (PyUnicode_GET_LENGTH(item) != 1)
8885 goto exit;
8886
8887 replace = PyUnicode_READ_CHAR(item, 0);
8888 if (replace > 127)
8889 goto exit;
8890 translate[ch] = (Py_UCS1)replace;
8891 }
8892 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008893 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008894 goto exit;
8895 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008896 ret = 1;
8897
Benjamin Peterson1365de72014-04-07 20:15:41 -04008898 exit:
8899 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008900 return ret;
8901}
8902
8903/* Fast path for ascii => ascii translation. Return 1 if the whole string
8904 was translated into writer, return 0 if the input string was partially
8905 translated into writer, raise an exception and return -1 on error. */
8906static int
8907unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008908 _PyUnicodeWriter *writer, int ignore,
8909 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008910{
Victor Stinner872b2912014-04-05 14:27:07 +02008911 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008912 Py_ssize_t len;
8913 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008914 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008915
Victor Stinner89a76ab2014-04-05 11:44:04 +02008916 len = PyUnicode_GET_LENGTH(input);
8917
Victor Stinner872b2912014-04-05 14:27:07 +02008918 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008919
8920 in = PyUnicode_1BYTE_DATA(input);
8921 end = in + len;
8922
8923 assert(PyUnicode_IS_ASCII(writer->buffer));
8924 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8925 out = PyUnicode_1BYTE_DATA(writer->buffer);
8926
Victor Stinner872b2912014-04-05 14:27:07 +02008927 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008928 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008929 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008930 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008931 int translate = unicode_fast_translate_lookup(mapping, ch,
8932 ascii_table);
8933 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008934 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008935 if (translate == 0)
8936 goto exit;
8937 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008938 }
Victor Stinner872b2912014-04-05 14:27:07 +02008939 if (ch2 == 0xfe) {
8940 if (ignore)
8941 continue;
8942 goto exit;
8943 }
8944 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008945 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008946 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008947 }
Victor Stinner872b2912014-04-05 14:27:07 +02008948 res = 1;
8949
8950exit:
8951 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008952 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008953 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008954}
8955
Victor Stinner3222da22015-10-01 22:07:32 +02008956static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008957_PyUnicode_TranslateCharmap(PyObject *input,
8958 PyObject *mapping,
8959 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008960{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008961 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008962 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008963 Py_ssize_t size, i;
8964 int kind;
8965 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008966 _PyUnicodeWriter writer;
8967 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008968 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008969 PyObject *errorHandler = NULL;
8970 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008971 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008972 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008973
Guido van Rossumd57fd912000-03-10 22:53:23 +00008974 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008975 PyErr_BadArgument();
8976 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008977 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008979 if (PyUnicode_READY(input) == -1)
8980 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008981 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008982 kind = PyUnicode_KIND(input);
8983 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008984
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008985 if (size == 0)
8986 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008987
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008988 /* allocate enough for a simple 1:1 translation without
8989 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008990 _PyUnicodeWriter_Init(&writer);
8991 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008992 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008993
Victor Stinner872b2912014-04-05 14:27:07 +02008994 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8995
Victor Stinner33798672016-03-01 21:59:58 +01008996 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008997 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008998 if (PyUnicode_IS_ASCII(input)) {
8999 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9000 if (res < 0) {
9001 _PyUnicodeWriter_Dealloc(&writer);
9002 return NULL;
9003 }
9004 if (res == 1)
9005 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009006 }
Victor Stinner33798672016-03-01 21:59:58 +01009007 else {
9008 i = 0;
9009 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009010
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009011 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009012 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009013 int translate;
9014 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9015 Py_ssize_t newpos;
9016 /* startpos for collecting untranslatable chars */
9017 Py_ssize_t collstart;
9018 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009019 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009020
Victor Stinner1194ea02014-04-04 19:37:40 +02009021 ch = PyUnicode_READ(kind, data, i);
9022 translate = charmaptranslate_output(ch, mapping, &writer);
9023 if (translate < 0)
9024 goto onError;
9025
9026 if (translate != 0) {
9027 /* it worked => adjust input pointer */
9028 ++i;
9029 continue;
9030 }
9031
9032 /* untranslatable character */
9033 collstart = i;
9034 collend = i+1;
9035
9036 /* find all untranslatable characters */
9037 while (collend < size) {
9038 PyObject *x;
9039 ch = PyUnicode_READ(kind, data, collend);
9040 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009041 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009042 Py_XDECREF(x);
9043 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009044 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009045 ++collend;
9046 }
9047
9048 if (ignore) {
9049 i = collend;
9050 }
9051 else {
9052 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9053 reason, input, &exc,
9054 collstart, collend, &newpos);
9055 if (repunicode == NULL)
9056 goto onError;
9057 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009058 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009059 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009060 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009061 Py_DECREF(repunicode);
9062 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009063 }
9064 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009065 Py_XDECREF(exc);
9066 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009067 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009068
Benjamin Peterson29060642009-01-31 22:14:21 +00009069 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009070 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009071 Py_XDECREF(exc);
9072 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009073 return NULL;
9074}
9075
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009076/* Deprecated. Use PyUnicode_Translate instead. */
9077PyObject *
9078PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9079 Py_ssize_t size,
9080 PyObject *mapping,
9081 const char *errors)
9082{
Christian Heimes5f520f42012-09-11 14:03:25 +02009083 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009084 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009085 if (!unicode)
9086 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009087 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9088 Py_DECREF(unicode);
9089 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009090}
9091
Alexander Belopolsky40018472011-02-26 01:02:56 +00009092PyObject *
9093PyUnicode_Translate(PyObject *str,
9094 PyObject *mapping,
9095 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009096{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009097 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009098 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009099 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009100}
Tim Petersced69f82003-09-16 20:30:58 +00009101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009102PyObject *
9103_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9104{
9105 if (!PyUnicode_Check(unicode)) {
9106 PyErr_BadInternalCall();
9107 return NULL;
9108 }
9109 if (PyUnicode_READY(unicode) == -1)
9110 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009111 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 /* If the string is already ASCII, just return the same string */
9113 Py_INCREF(unicode);
9114 return unicode;
9115 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009116
9117 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9118 PyObject *result = PyUnicode_New(len, 127);
9119 if (result == NULL) {
9120 return NULL;
9121 }
9122
9123 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9124 int kind = PyUnicode_KIND(unicode);
9125 const void *data = PyUnicode_DATA(unicode);
9126 Py_ssize_t i;
9127 for (i = 0; i < len; ++i) {
9128 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9129 if (ch < 127) {
9130 out[i] = ch;
9131 }
9132 else if (Py_UNICODE_ISSPACE(ch)) {
9133 out[i] = ' ';
9134 }
9135 else {
9136 int decimal = Py_UNICODE_TODECIMAL(ch);
9137 if (decimal < 0) {
9138 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009139 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009140 _PyUnicode_LENGTH(result) = i + 1;
9141 break;
9142 }
9143 out[i] = '0' + decimal;
9144 }
9145 }
9146
INADA Naoki16dfca42018-07-14 12:06:43 +09009147 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009148 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009149}
9150
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009151PyObject *
9152PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9153 Py_ssize_t length)
9154{
Victor Stinnerf0124502011-11-21 23:12:56 +01009155 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009156 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009157 Py_UCS4 maxchar;
9158 enum PyUnicode_Kind kind;
9159 void *data;
9160
Victor Stinner99d7ad02012-02-22 13:37:39 +01009161 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009162 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009163 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009164 if (ch > 127) {
9165 int decimal = Py_UNICODE_TODECIMAL(ch);
9166 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009167 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009168 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009169 }
9170 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009171
9172 /* Copy to a new string */
9173 decimal = PyUnicode_New(length, maxchar);
9174 if (decimal == NULL)
9175 return decimal;
9176 kind = PyUnicode_KIND(decimal);
9177 data = PyUnicode_DATA(decimal);
9178 /* Iterate over code points */
9179 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009180 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009181 if (ch > 127) {
9182 int decimal = Py_UNICODE_TODECIMAL(ch);
9183 if (decimal >= 0)
9184 ch = '0' + decimal;
9185 }
9186 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009187 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009188 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009189}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009190/* --- Decimal Encoder ---------------------------------------------------- */
9191
Alexander Belopolsky40018472011-02-26 01:02:56 +00009192int
9193PyUnicode_EncodeDecimal(Py_UNICODE *s,
9194 Py_ssize_t length,
9195 char *output,
9196 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009197{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009198 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009199 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009200 enum PyUnicode_Kind kind;
9201 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009202
9203 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009204 PyErr_BadArgument();
9205 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009206 }
9207
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009208 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009209 if (unicode == NULL)
9210 return -1;
9211
Victor Stinner42bf7752011-11-21 22:52:58 +01009212 kind = PyUnicode_KIND(unicode);
9213 data = PyUnicode_DATA(unicode);
9214
Victor Stinnerb84d7232011-11-22 01:50:07 +01009215 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009216 PyObject *exc;
9217 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009218 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009219 Py_ssize_t startpos;
9220
9221 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009222
Benjamin Peterson29060642009-01-31 22:14:21 +00009223 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009224 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009225 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009226 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009227 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009228 decimal = Py_UNICODE_TODECIMAL(ch);
9229 if (decimal >= 0) {
9230 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009231 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009232 continue;
9233 }
9234 if (0 < ch && ch < 256) {
9235 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009236 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009237 continue;
9238 }
Victor Stinner6345be92011-11-25 20:09:01 +01009239
Victor Stinner42bf7752011-11-21 22:52:58 +01009240 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009241 exc = NULL;
9242 raise_encode_exception(&exc, "decimal", unicode,
9243 startpos, startpos+1,
9244 "invalid decimal Unicode string");
9245 Py_XDECREF(exc);
9246 Py_DECREF(unicode);
9247 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009248 }
9249 /* 0-terminate the output string */
9250 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009251 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009252 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009253}
9254
Guido van Rossumd57fd912000-03-10 22:53:23 +00009255/* --- Helpers ------------------------------------------------------------ */
9256
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009257/* helper macro to fixup start/end slice values */
9258#define ADJUST_INDICES(start, end, len) \
9259 if (end > len) \
9260 end = len; \
9261 else if (end < 0) { \
9262 end += len; \
9263 if (end < 0) \
9264 end = 0; \
9265 } \
9266 if (start < 0) { \
9267 start += len; \
9268 if (start < 0) \
9269 start = 0; \
9270 }
9271
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009272static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009273any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009274 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009275 Py_ssize_t end,
9276 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009277{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009278 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009279 void *buf1, *buf2;
9280 Py_ssize_t len1, len2, result;
9281
9282 kind1 = PyUnicode_KIND(s1);
9283 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009284 if (kind1 < kind2)
9285 return -1;
9286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 len1 = PyUnicode_GET_LENGTH(s1);
9288 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009289 ADJUST_INDICES(start, end, len1);
9290 if (end - start < len2)
9291 return -1;
9292
9293 buf1 = PyUnicode_DATA(s1);
9294 buf2 = PyUnicode_DATA(s2);
9295 if (len2 == 1) {
9296 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9297 result = findchar((const char *)buf1 + kind1*start,
9298 kind1, end - start, ch, direction);
9299 if (result == -1)
9300 return -1;
9301 else
9302 return start + result;
9303 }
9304
9305 if (kind2 != kind1) {
9306 buf2 = _PyUnicode_AsKind(s2, kind1);
9307 if (!buf2)
9308 return -2;
9309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009310
Victor Stinner794d5672011-10-10 03:21:36 +02009311 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009312 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009313 case PyUnicode_1BYTE_KIND:
9314 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9315 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9316 else
9317 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9318 break;
9319 case PyUnicode_2BYTE_KIND:
9320 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9321 break;
9322 case PyUnicode_4BYTE_KIND:
9323 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9324 break;
9325 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009326 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009327 }
9328 }
9329 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009330 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009331 case PyUnicode_1BYTE_KIND:
9332 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9333 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9334 else
9335 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9336 break;
9337 case PyUnicode_2BYTE_KIND:
9338 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9339 break;
9340 case PyUnicode_4BYTE_KIND:
9341 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9342 break;
9343 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009344 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009345 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 }
9347
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009348 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009349 PyMem_Free(buf2);
9350
9351 return result;
9352}
9353
Victor Stinner59423e32018-11-26 13:40:01 +01009354/* _PyUnicode_InsertThousandsGrouping() helper functions */
9355#include "stringlib/localeutil.h"
9356
9357/**
9358 * InsertThousandsGrouping:
9359 * @writer: Unicode writer.
9360 * @n_buffer: Number of characters in @buffer.
9361 * @digits: Digits we're reading from. If count is non-NULL, this is unused.
9362 * @d_pos: Start of digits string.
9363 * @n_digits: The number of digits in the string, in which we want
9364 * to put the grouping chars.
9365 * @min_width: The minimum width of the digits in the output string.
9366 * Output will be zero-padded on the left to fill.
9367 * @grouping: see definition in localeconv().
9368 * @thousands_sep: see definition in localeconv().
9369 *
9370 * There are 2 modes: counting and filling. If @writer is NULL,
9371 * we are in counting mode, else filling mode.
9372 * If counting, the required buffer size is returned.
9373 * If filling, we know the buffer will be large enough, so we don't
9374 * need to pass in the buffer size.
9375 * Inserts thousand grouping characters (as defined by grouping and
9376 * thousands_sep) into @writer.
9377 *
9378 * Return value: -1 on error, number of characters otherwise.
9379 **/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009380Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009381_PyUnicode_InsertThousandsGrouping(
Victor Stinner59423e32018-11-26 13:40:01 +01009382 _PyUnicodeWriter *writer,
Victor Stinner41a863c2012-02-24 00:37:51 +01009383 Py_ssize_t n_buffer,
Victor Stinner59423e32018-11-26 13:40:01 +01009384 PyObject *digits,
9385 Py_ssize_t d_pos,
9386 Py_ssize_t n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009387 Py_ssize_t min_width,
Victor Stinner59423e32018-11-26 13:40:01 +01009388 const char *grouping,
9389 PyObject *thousands_sep,
Victor Stinner41a863c2012-02-24 00:37:51 +01009390 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009391{
Victor Stinner59423e32018-11-26 13:40:01 +01009392 if (writer) {
9393 assert(digits != NULL);
9394 assert(maxchar == NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009395 }
9396 else {
Victor Stinner59423e32018-11-26 13:40:01 +01009397 assert(digits == NULL);
9398 assert(maxchar != NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009399 }
Victor Stinner59423e32018-11-26 13:40:01 +01009400 assert(0 <= d_pos);
9401 assert(0 <= n_digits);
9402 assert(0 <= min_width);
9403 assert(grouping != NULL);
9404
9405 if (digits != NULL) {
9406 if (PyUnicode_READY(digits) == -1) {
9407 return -1;
Victor Stinner90f50d42012-02-24 01:44:47 +01009408 }
Victor Stinner59423e32018-11-26 13:40:01 +01009409 }
9410 if (PyUnicode_READY(thousands_sep) == -1) {
9411 return -1;
Victor Stinner41a863c2012-02-24 00:37:51 +01009412 }
9413
Victor Stinner59423e32018-11-26 13:40:01 +01009414 Py_ssize_t count = 0;
9415 Py_ssize_t n_zeros;
9416 int loop_broken = 0;
9417 int use_separator = 0; /* First time through, don't append the
9418 separator. They only go between
9419 groups. */
9420 Py_ssize_t buffer_pos;
9421 Py_ssize_t digits_pos;
9422 Py_ssize_t len;
9423 Py_ssize_t n_chars;
9424 Py_ssize_t remaining = n_digits; /* Number of chars remaining to
9425 be looked at */
9426 /* A generator that returns all of the grouping widths, until it
9427 returns 0. */
9428 GroupGenerator groupgen;
9429 GroupGenerator_init(&groupgen, grouping);
9430 const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9431
9432 /* if digits are not grouped, thousands separator
9433 should be an empty string */
9434 assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
9435
9436 digits_pos = d_pos + n_digits;
9437 if (writer) {
9438 buffer_pos = writer->pos + n_buffer;
9439 assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
9440 assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441 }
Victor Stinner59423e32018-11-26 13:40:01 +01009442 else {
9443 buffer_pos = n_buffer;
Victor Stinner90f50d42012-02-24 01:44:47 +01009444 }
Victor Stinner59423e32018-11-26 13:40:01 +01009445
9446 if (!writer) {
Victor Stinner41a863c2012-02-24 00:37:51 +01009447 *maxchar = 127;
Victor Stinner41a863c2012-02-24 00:37:51 +01009448 }
Victor Stinner59423e32018-11-26 13:40:01 +01009449
9450 while ((len = GroupGenerator_next(&groupgen)) > 0) {
9451 len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
9452 n_zeros = Py_MAX(0, len - remaining);
9453 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9454
9455 /* Use n_zero zero's and n_chars chars */
9456
9457 /* Count only, don't do anything. */
9458 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9459
9460 /* Copy into the writer. */
9461 InsertThousandsGrouping_fill(writer, &buffer_pos,
9462 digits, &digits_pos,
9463 n_chars, n_zeros,
9464 use_separator ? thousands_sep : NULL,
9465 thousands_sep_len, maxchar);
9466
9467 /* Use a separator next time. */
9468 use_separator = 1;
9469
9470 remaining -= n_chars;
9471 min_width -= len;
9472
9473 if (remaining <= 0 && min_width <= 0) {
9474 loop_broken = 1;
9475 break;
9476 }
9477 min_width -= thousands_sep_len;
9478 }
9479 if (!loop_broken) {
9480 /* We left the loop without using a break statement. */
9481
9482 len = Py_MAX(Py_MAX(remaining, min_width), 1);
9483 n_zeros = Py_MAX(0, len - remaining);
9484 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9485
9486 /* Use n_zero zero's and n_chars chars */
9487 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9488
9489 /* Copy into the writer. */
9490 InsertThousandsGrouping_fill(writer, &buffer_pos,
9491 digits, &digits_pos,
9492 n_chars, n_zeros,
9493 use_separator ? thousands_sep : NULL,
9494 thousands_sep_len, maxchar);
9495 }
9496 return count;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009497}
9498
9499
Alexander Belopolsky40018472011-02-26 01:02:56 +00009500Py_ssize_t
9501PyUnicode_Count(PyObject *str,
9502 PyObject *substr,
9503 Py_ssize_t start,
9504 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009506 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009507 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 void *buf1 = NULL, *buf2 = NULL;
9509 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009510
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009511 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009512 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009513
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009514 kind1 = PyUnicode_KIND(str);
9515 kind2 = PyUnicode_KIND(substr);
9516 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009517 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009518
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009519 len1 = PyUnicode_GET_LENGTH(str);
9520 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009521 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009522 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009523 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009524
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009525 buf1 = PyUnicode_DATA(str);
9526 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009527 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009528 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009529 if (!buf2)
9530 goto onError;
9531 }
9532
9533 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009534 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009535 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009536 result = asciilib_count(
9537 ((Py_UCS1*)buf1) + start, end - start,
9538 buf2, len2, PY_SSIZE_T_MAX
9539 );
9540 else
9541 result = ucs1lib_count(
9542 ((Py_UCS1*)buf1) + start, end - start,
9543 buf2, len2, PY_SSIZE_T_MAX
9544 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 break;
9546 case PyUnicode_2BYTE_KIND:
9547 result = ucs2lib_count(
9548 ((Py_UCS2*)buf1) + start, end - start,
9549 buf2, len2, PY_SSIZE_T_MAX
9550 );
9551 break;
9552 case PyUnicode_4BYTE_KIND:
9553 result = ucs4lib_count(
9554 ((Py_UCS4*)buf1) + start, end - start,
9555 buf2, len2, PY_SSIZE_T_MAX
9556 );
9557 break;
9558 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009559 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009560 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009561
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009562 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009563 PyMem_Free(buf2);
9564
Guido van Rossumd57fd912000-03-10 22:53:23 +00009565 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009567 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009568 PyMem_Free(buf2);
9569 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009570}
9571
Alexander Belopolsky40018472011-02-26 01:02:56 +00009572Py_ssize_t
9573PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009574 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009575 Py_ssize_t start,
9576 Py_ssize_t end,
9577 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009578{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009579 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009580 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009581
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009582 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583}
9584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585Py_ssize_t
9586PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9587 Py_ssize_t start, Py_ssize_t end,
9588 int direction)
9589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009591 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592 if (PyUnicode_READY(str) == -1)
9593 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009594 len = PyUnicode_GET_LENGTH(str);
9595 ADJUST_INDICES(start, end, len);
9596 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009597 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009598 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009599 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9600 kind, end-start, ch, direction);
9601 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009602 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009603 else
9604 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605}
9606
Alexander Belopolsky40018472011-02-26 01:02:56 +00009607static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009608tailmatch(PyObject *self,
9609 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009610 Py_ssize_t start,
9611 Py_ssize_t end,
9612 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009613{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009614 int kind_self;
9615 int kind_sub;
9616 void *data_self;
9617 void *data_sub;
9618 Py_ssize_t offset;
9619 Py_ssize_t i;
9620 Py_ssize_t end_sub;
9621
9622 if (PyUnicode_READY(self) == -1 ||
9623 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009624 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009626 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9627 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009628 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009629 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009630
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009631 if (PyUnicode_GET_LENGTH(substring) == 0)
9632 return 1;
9633
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 kind_self = PyUnicode_KIND(self);
9635 data_self = PyUnicode_DATA(self);
9636 kind_sub = PyUnicode_KIND(substring);
9637 data_sub = PyUnicode_DATA(substring);
9638 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9639
9640 if (direction > 0)
9641 offset = end;
9642 else
9643 offset = start;
9644
9645 if (PyUnicode_READ(kind_self, data_self, offset) ==
9646 PyUnicode_READ(kind_sub, data_sub, 0) &&
9647 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9648 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9649 /* If both are of the same kind, memcmp is sufficient */
9650 if (kind_self == kind_sub) {
9651 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009652 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 data_sub,
9654 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009655 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009656 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009657 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009658 else {
9659 /* We do not need to compare 0 and len(substring)-1 because
9660 the if statement above ensured already that they are equal
9661 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009662 for (i = 1; i < end_sub; ++i) {
9663 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9664 PyUnicode_READ(kind_sub, data_sub, i))
9665 return 0;
9666 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009667 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009668 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669 }
9670
9671 return 0;
9672}
9673
Alexander Belopolsky40018472011-02-26 01:02:56 +00009674Py_ssize_t
9675PyUnicode_Tailmatch(PyObject *str,
9676 PyObject *substr,
9677 Py_ssize_t start,
9678 Py_ssize_t end,
9679 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009680{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009681 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009682 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009683
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009684 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009685}
9686
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009687static PyObject *
9688ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009689{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009690 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9691 char *resdata, *data = PyUnicode_DATA(self);
9692 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009693
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009694 res = PyUnicode_New(len, 127);
9695 if (res == NULL)
9696 return NULL;
9697 resdata = PyUnicode_DATA(res);
9698 if (lower)
9699 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009700 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009701 _Py_bytes_upper(resdata, data, len);
9702 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009703}
9704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009705static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009706handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009707{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009708 Py_ssize_t j;
9709 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009710 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009711 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009712
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009713 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9714
9715 where ! is a negation and \p{xxx} is a character with property xxx.
9716 */
9717 for (j = i - 1; j >= 0; j--) {
9718 c = PyUnicode_READ(kind, data, j);
9719 if (!_PyUnicode_IsCaseIgnorable(c))
9720 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009721 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009722 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9723 if (final_sigma) {
9724 for (j = i + 1; j < length; j++) {
9725 c = PyUnicode_READ(kind, data, j);
9726 if (!_PyUnicode_IsCaseIgnorable(c))
9727 break;
9728 }
9729 final_sigma = j == length || !_PyUnicode_IsCased(c);
9730 }
9731 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009732}
9733
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009734static int
9735lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9736 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009737{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009738 /* Obscure special case. */
9739 if (c == 0x3A3) {
9740 mapped[0] = handle_capital_sigma(kind, data, length, i);
9741 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009742 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009743 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009744}
9745
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009746static Py_ssize_t
9747do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009748{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009749 Py_ssize_t i, k = 0;
9750 int n_res, j;
9751 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009752
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009753 c = PyUnicode_READ(kind, data, 0);
9754 n_res = _PyUnicode_ToUpperFull(c, mapped);
9755 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009756 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009757 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009758 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009759 for (i = 1; i < length; i++) {
9760 c = PyUnicode_READ(kind, data, i);
9761 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9762 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009763 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009764 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009765 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009766 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009767 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009768}
9769
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009770static Py_ssize_t
9771do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9772 Py_ssize_t i, k = 0;
9773
9774 for (i = 0; i < length; i++) {
9775 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9776 int n_res, j;
9777 if (Py_UNICODE_ISUPPER(c)) {
9778 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9779 }
9780 else if (Py_UNICODE_ISLOWER(c)) {
9781 n_res = _PyUnicode_ToUpperFull(c, mapped);
9782 }
9783 else {
9784 n_res = 1;
9785 mapped[0] = c;
9786 }
9787 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009788 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009789 res[k++] = mapped[j];
9790 }
9791 }
9792 return k;
9793}
9794
9795static Py_ssize_t
9796do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9797 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009799 Py_ssize_t i, k = 0;
9800
9801 for (i = 0; i < length; i++) {
9802 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9803 int n_res, j;
9804 if (lower)
9805 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9806 else
9807 n_res = _PyUnicode_ToUpperFull(c, mapped);
9808 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009809 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009810 res[k++] = mapped[j];
9811 }
9812 }
9813 return k;
9814}
9815
9816static Py_ssize_t
9817do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9818{
9819 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9820}
9821
9822static Py_ssize_t
9823do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9824{
9825 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9826}
9827
Benjamin Petersone51757f2012-01-12 21:10:29 -05009828static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009829do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9830{
9831 Py_ssize_t i, k = 0;
9832
9833 for (i = 0; i < length; i++) {
9834 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9835 Py_UCS4 mapped[3];
9836 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9837 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009838 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009839 res[k++] = mapped[j];
9840 }
9841 }
9842 return k;
9843}
9844
9845static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009846do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9847{
9848 Py_ssize_t i, k = 0;
9849 int previous_is_cased;
9850
9851 previous_is_cased = 0;
9852 for (i = 0; i < length; i++) {
9853 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9854 Py_UCS4 mapped[3];
9855 int n_res, j;
9856
9857 if (previous_is_cased)
9858 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9859 else
9860 n_res = _PyUnicode_ToTitleFull(c, mapped);
9861
9862 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009863 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009864 res[k++] = mapped[j];
9865 }
9866
9867 previous_is_cased = _PyUnicode_IsCased(c);
9868 }
9869 return k;
9870}
9871
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009872static PyObject *
9873case_operation(PyObject *self,
9874 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9875{
9876 PyObject *res = NULL;
9877 Py_ssize_t length, newlength = 0;
9878 int kind, outkind;
9879 void *data, *outdata;
9880 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9881
Benjamin Petersoneea48462012-01-16 14:28:50 -05009882 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009883
9884 kind = PyUnicode_KIND(self);
9885 data = PyUnicode_DATA(self);
9886 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009887 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009888 PyErr_SetString(PyExc_OverflowError, "string is too long");
9889 return NULL;
9890 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009891 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009892 if (tmp == NULL)
9893 return PyErr_NoMemory();
9894 newlength = perform(kind, data, length, tmp, &maxchar);
9895 res = PyUnicode_New(newlength, maxchar);
9896 if (res == NULL)
9897 goto leave;
9898 tmpend = tmp + newlength;
9899 outdata = PyUnicode_DATA(res);
9900 outkind = PyUnicode_KIND(res);
9901 switch (outkind) {
9902 case PyUnicode_1BYTE_KIND:
9903 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9904 break;
9905 case PyUnicode_2BYTE_KIND:
9906 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9907 break;
9908 case PyUnicode_4BYTE_KIND:
9909 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9910 break;
9911 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009912 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009913 }
9914 leave:
9915 PyMem_FREE(tmp);
9916 return res;
9917}
9918
Tim Peters8ce9f162004-08-27 01:49:32 +00009919PyObject *
9920PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009921{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009922 PyObject *res;
9923 PyObject *fseq;
9924 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009925 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009926
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009927 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009928 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009929 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009930 }
9931
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009932 /* NOTE: the following code can't call back into Python code,
9933 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009934 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009935
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009936 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009937 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009938 res = _PyUnicode_JoinArray(separator, items, seqlen);
9939 Py_DECREF(fseq);
9940 return res;
9941}
9942
9943PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009944_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009945{
9946 PyObject *res = NULL; /* the result */
9947 PyObject *sep = NULL;
9948 Py_ssize_t seplen;
9949 PyObject *item;
9950 Py_ssize_t sz, i, res_offset;
9951 Py_UCS4 maxchar;
9952 Py_UCS4 item_maxchar;
9953 int use_memcpy;
9954 unsigned char *res_data = NULL, *sep_data = NULL;
9955 PyObject *last_obj;
9956 unsigned int kind = 0;
9957
Tim Peters05eba1f2004-08-27 21:32:02 +00009958 /* If empty sequence, return u"". */
9959 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009960 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009961 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009962
Tim Peters05eba1f2004-08-27 21:32:02 +00009963 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009964 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009965 if (seqlen == 1) {
9966 if (PyUnicode_CheckExact(items[0])) {
9967 res = items[0];
9968 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009969 return res;
9970 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009971 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009972 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009973 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009974 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009975 /* Set up sep and seplen */
9976 if (separator == NULL) {
9977 /* fall back to a blank space separator */
9978 sep = PyUnicode_FromOrdinal(' ');
9979 if (!sep)
9980 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009981 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009982 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009983 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009984 else {
9985 if (!PyUnicode_Check(separator)) {
9986 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009987 "separator: expected str instance,"
9988 " %.80s found",
9989 Py_TYPE(separator)->tp_name);
Victor Stinneracf47b82011-10-06 12:32:37 +02009990 goto onError;
9991 }
9992 if (PyUnicode_READY(separator))
9993 goto onError;
9994 sep = separator;
9995 seplen = PyUnicode_GET_LENGTH(separator);
9996 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9997 /* inc refcount to keep this code path symmetric with the
9998 above case of a blank separator */
9999 Py_INCREF(sep);
10000 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010001 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010002 }
10003
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010004 /* There are at least two things to join, or else we have a subclass
10005 * of str in the sequence.
10006 * Do a pre-pass to figure out the total amount of space we'll
10007 * need (sz), and see whether all argument are strings.
10008 */
10009 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010010#ifdef Py_DEBUG
10011 use_memcpy = 0;
10012#else
10013 use_memcpy = 1;
10014#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010015 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010016 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010017 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010018 if (!PyUnicode_Check(item)) {
10019 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020010020 "sequence item %zd: expected str instance,"
10021 " %.80s found",
10022 i, Py_TYPE(item)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000010023 goto onError;
10024 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010025 if (PyUnicode_READY(item) == -1)
10026 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010027 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010029 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010030 if (i != 0) {
10031 add_sz += seplen;
10032 }
10033 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010034 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010035 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010036 goto onError;
10037 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010038 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010039 if (use_memcpy && last_obj != NULL) {
10040 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10041 use_memcpy = 0;
10042 }
10043 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010044 }
Tim Petersced69f82003-09-16 20:30:58 +000010045
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010046 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010047 if (res == NULL)
10048 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010049
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010050 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010051#ifdef Py_DEBUG
10052 use_memcpy = 0;
10053#else
10054 if (use_memcpy) {
10055 res_data = PyUnicode_1BYTE_DATA(res);
10056 kind = PyUnicode_KIND(res);
10057 if (seplen != 0)
10058 sep_data = PyUnicode_1BYTE_DATA(sep);
10059 }
10060#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010061 if (use_memcpy) {
10062 for (i = 0; i < seqlen; ++i) {
10063 Py_ssize_t itemlen;
10064 item = items[i];
10065
10066 /* Copy item, and maybe the separator. */
10067 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010068 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010069 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010070 kind * seplen);
10071 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010072 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010073
10074 itemlen = PyUnicode_GET_LENGTH(item);
10075 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010076 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010077 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010078 kind * itemlen);
10079 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010080 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010081 }
10082 assert(res_data == PyUnicode_1BYTE_DATA(res)
10083 + kind * PyUnicode_GET_LENGTH(res));
10084 }
10085 else {
10086 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10087 Py_ssize_t itemlen;
10088 item = items[i];
10089
10090 /* Copy item, and maybe the separator. */
10091 if (i && seplen != 0) {
10092 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10093 res_offset += seplen;
10094 }
10095
10096 itemlen = PyUnicode_GET_LENGTH(item);
10097 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010098 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010099 res_offset += itemlen;
10100 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010101 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010102 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010103 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010106 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010108
Benjamin Peterson29060642009-01-31 22:14:21 +000010109 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010111 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010112 return NULL;
10113}
10114
Victor Stinnerd3f08822012-05-29 12:57:52 +020010115void
10116_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10117 Py_UCS4 fill_char)
10118{
10119 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
10120 const void *data = PyUnicode_DATA(unicode);
10121 assert(PyUnicode_IS_READY(unicode));
10122 assert(unicode_modifiable(unicode));
10123 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10124 assert(start >= 0);
10125 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner59423e32018-11-26 13:40:01 +010010126 unicode_fill(kind, data, fill_char, start, length);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010127}
10128
Victor Stinner3fe55312012-01-04 00:33:50 +010010129Py_ssize_t
10130PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10131 Py_UCS4 fill_char)
10132{
10133 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010134
10135 if (!PyUnicode_Check(unicode)) {
10136 PyErr_BadInternalCall();
10137 return -1;
10138 }
10139 if (PyUnicode_READY(unicode) == -1)
10140 return -1;
10141 if (unicode_check_modifiable(unicode))
10142 return -1;
10143
Victor Stinnerd3f08822012-05-29 12:57:52 +020010144 if (start < 0) {
10145 PyErr_SetString(PyExc_IndexError, "string index out of range");
10146 return -1;
10147 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010148 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10149 PyErr_SetString(PyExc_ValueError,
10150 "fill character is bigger than "
10151 "the string maximum character");
10152 return -1;
10153 }
10154
10155 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10156 length = Py_MIN(maxlen, length);
10157 if (length <= 0)
10158 return 0;
10159
Victor Stinnerd3f08822012-05-29 12:57:52 +020010160 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010161 return length;
10162}
10163
Victor Stinner9310abb2011-10-05 00:59:23 +020010164static PyObject *
10165pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010166 Py_ssize_t left,
10167 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010169{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 PyObject *u;
10171 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010172 int kind;
10173 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010174
10175 if (left < 0)
10176 left = 0;
10177 if (right < 0)
10178 right = 0;
10179
Victor Stinnerc4b49542011-12-11 22:44:26 +010010180 if (left == 0 && right == 0)
10181 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10184 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010185 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10186 return NULL;
10187 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010189 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010190 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010191 if (!u)
10192 return NULL;
10193
10194 kind = PyUnicode_KIND(u);
10195 data = PyUnicode_DATA(u);
10196 if (left)
Victor Stinner59423e32018-11-26 13:40:01 +010010197 unicode_fill(kind, data, fill, 0, left);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010198 if (right)
Victor Stinner59423e32018-11-26 13:40:01 +010010199 unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010200 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010201 assert(_PyUnicode_CheckConsistency(u, 1));
10202 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010203}
10204
Alexander Belopolsky40018472011-02-26 01:02:56 +000010205PyObject *
10206PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010207{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010208 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010210 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010211 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010212
Benjamin Petersonead6b532011-12-20 17:23:42 -060010213 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010214 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010215 if (PyUnicode_IS_ASCII(string))
10216 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010217 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010218 PyUnicode_GET_LENGTH(string), keepends);
10219 else
10220 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010221 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010222 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 break;
10224 case PyUnicode_2BYTE_KIND:
10225 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010226 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 PyUnicode_GET_LENGTH(string), keepends);
10228 break;
10229 case PyUnicode_4BYTE_KIND:
10230 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010231 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 PyUnicode_GET_LENGTH(string), keepends);
10233 break;
10234 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010235 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010237 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010238}
10239
Alexander Belopolsky40018472011-02-26 01:02:56 +000010240static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010241split(PyObject *self,
10242 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010243 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010244{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010245 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 void *buf1, *buf2;
10247 Py_ssize_t len1, len2;
10248 PyObject* out;
10249
Guido van Rossumd57fd912000-03-10 22:53:23 +000010250 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010251 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 if (PyUnicode_READY(self) == -1)
10254 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010255
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010257 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010259 if (PyUnicode_IS_ASCII(self))
10260 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010261 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010262 PyUnicode_GET_LENGTH(self), maxcount
10263 );
10264 else
10265 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010266 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010267 PyUnicode_GET_LENGTH(self), maxcount
10268 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 case PyUnicode_2BYTE_KIND:
10270 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010271 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 PyUnicode_GET_LENGTH(self), maxcount
10273 );
10274 case PyUnicode_4BYTE_KIND:
10275 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010276 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 PyUnicode_GET_LENGTH(self), maxcount
10278 );
10279 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010280 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 }
10282
10283 if (PyUnicode_READY(substring) == -1)
10284 return NULL;
10285
10286 kind1 = PyUnicode_KIND(self);
10287 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 len1 = PyUnicode_GET_LENGTH(self);
10289 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010290 if (kind1 < kind2 || len1 < len2) {
10291 out = PyList_New(1);
10292 if (out == NULL)
10293 return NULL;
10294 Py_INCREF(self);
10295 PyList_SET_ITEM(out, 0, self);
10296 return out;
10297 }
10298 buf1 = PyUnicode_DATA(self);
10299 buf2 = PyUnicode_DATA(substring);
10300 if (kind2 != kind1) {
10301 buf2 = _PyUnicode_AsKind(substring, kind1);
10302 if (!buf2)
10303 return NULL;
10304 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010306 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010308 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10309 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010310 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010311 else
10312 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010313 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 break;
10315 case PyUnicode_2BYTE_KIND:
10316 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010317 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 break;
10319 case PyUnicode_4BYTE_KIND:
10320 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010321 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 break;
10323 default:
10324 out = NULL;
10325 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010326 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 PyMem_Free(buf2);
10328 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010329}
10330
Alexander Belopolsky40018472011-02-26 01:02:56 +000010331static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010332rsplit(PyObject *self,
10333 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010334 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010335{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010336 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 void *buf1, *buf2;
10338 Py_ssize_t len1, len2;
10339 PyObject* out;
10340
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010341 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010342 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010343
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010344 if (PyUnicode_READY(self) == -1)
10345 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010347 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010348 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010349 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010350 if (PyUnicode_IS_ASCII(self))
10351 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010352 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010353 PyUnicode_GET_LENGTH(self), maxcount
10354 );
10355 else
10356 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010357 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010358 PyUnicode_GET_LENGTH(self), maxcount
10359 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010360 case PyUnicode_2BYTE_KIND:
10361 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010362 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 PyUnicode_GET_LENGTH(self), maxcount
10364 );
10365 case PyUnicode_4BYTE_KIND:
10366 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010367 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 PyUnicode_GET_LENGTH(self), maxcount
10369 );
10370 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010371 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 }
10373
10374 if (PyUnicode_READY(substring) == -1)
10375 return NULL;
10376
10377 kind1 = PyUnicode_KIND(self);
10378 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 len1 = PyUnicode_GET_LENGTH(self);
10380 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010381 if (kind1 < kind2 || len1 < len2) {
10382 out = PyList_New(1);
10383 if (out == NULL)
10384 return NULL;
10385 Py_INCREF(self);
10386 PyList_SET_ITEM(out, 0, self);
10387 return out;
10388 }
10389 buf1 = PyUnicode_DATA(self);
10390 buf2 = PyUnicode_DATA(substring);
10391 if (kind2 != kind1) {
10392 buf2 = _PyUnicode_AsKind(substring, kind1);
10393 if (!buf2)
10394 return NULL;
10395 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010397 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010399 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10400 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010401 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010402 else
10403 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010404 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 break;
10406 case PyUnicode_2BYTE_KIND:
10407 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010408 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 break;
10410 case PyUnicode_4BYTE_KIND:
10411 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010412 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 break;
10414 default:
10415 out = NULL;
10416 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010417 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 PyMem_Free(buf2);
10419 return out;
10420}
10421
10422static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010423anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10424 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010426 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010428 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10429 return asciilib_find(buf1, len1, buf2, len2, offset);
10430 else
10431 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 case PyUnicode_2BYTE_KIND:
10433 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10434 case PyUnicode_4BYTE_KIND:
10435 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10436 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010437 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438}
10439
10440static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010441anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10442 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010444 switch (kind) {
10445 case PyUnicode_1BYTE_KIND:
10446 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10447 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10448 else
10449 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10450 case PyUnicode_2BYTE_KIND:
10451 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10452 case PyUnicode_4BYTE_KIND:
10453 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10454 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010455 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010456}
10457
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010458static void
10459replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10460 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10461{
10462 int kind = PyUnicode_KIND(u);
10463 void *data = PyUnicode_DATA(u);
10464 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10465 if (kind == PyUnicode_1BYTE_KIND) {
10466 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10467 (Py_UCS1 *)data + len,
10468 u1, u2, maxcount);
10469 }
10470 else if (kind == PyUnicode_2BYTE_KIND) {
10471 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10472 (Py_UCS2 *)data + len,
10473 u1, u2, maxcount);
10474 }
10475 else {
10476 assert(kind == PyUnicode_4BYTE_KIND);
10477 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10478 (Py_UCS4 *)data + len,
10479 u1, u2, maxcount);
10480 }
10481}
10482
Alexander Belopolsky40018472011-02-26 01:02:56 +000010483static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484replace(PyObject *self, PyObject *str1,
10485 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 PyObject *u;
10488 char *sbuf = PyUnicode_DATA(self);
10489 char *buf1 = PyUnicode_DATA(str1);
10490 char *buf2 = PyUnicode_DATA(str2);
10491 int srelease = 0, release1 = 0, release2 = 0;
10492 int skind = PyUnicode_KIND(self);
10493 int kind1 = PyUnicode_KIND(str1);
10494 int kind2 = PyUnicode_KIND(str2);
10495 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10496 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10497 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010498 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010499 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010500
10501 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010502 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010503 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010504 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010505
Victor Stinner59de0ee2011-10-07 10:01:28 +020010506 if (str1 == str2)
10507 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010508
Victor Stinner49a0a212011-10-12 23:46:10 +020010509 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010510 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10511 if (maxchar < maxchar_str1)
10512 /* substring too wide to be present */
10513 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010514 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10515 /* Replacing str1 with str2 may cause a maxchar reduction in the
10516 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010517 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010518 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010520 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010521 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010523 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010525 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010526 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010527 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010528
Victor Stinner69ed0f42013-04-09 21:48:24 +020010529 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010530 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010531 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010532 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010533 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010535 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010537
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010538 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10539 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010540 }
10541 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010542 int rkind = skind;
10543 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010544 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 if (kind1 < rkind) {
10547 /* widen substring */
10548 buf1 = _PyUnicode_AsKind(str1, rkind);
10549 if (!buf1) goto error;
10550 release1 = 1;
10551 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010552 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010553 if (i < 0)
10554 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 if (rkind > kind2) {
10556 /* widen replacement */
10557 buf2 = _PyUnicode_AsKind(str2, rkind);
10558 if (!buf2) goto error;
10559 release2 = 1;
10560 }
10561 else if (rkind < kind2) {
10562 /* widen self and buf1 */
10563 rkind = kind2;
10564 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010565 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 sbuf = _PyUnicode_AsKind(self, rkind);
10567 if (!sbuf) goto error;
10568 srelease = 1;
10569 buf1 = _PyUnicode_AsKind(str1, rkind);
10570 if (!buf1) goto error;
10571 release1 = 1;
10572 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010573 u = PyUnicode_New(slen, maxchar);
10574 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010575 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010576 assert(PyUnicode_KIND(u) == rkind);
10577 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010578
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010579 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010580 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010581 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010583 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010584 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010585
10586 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010587 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010588 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010589 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010590 if (i == -1)
10591 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010592 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010594 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010595 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010596 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010597 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010598 }
10599 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010601 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 int rkind = skind;
10603 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010606 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 buf1 = _PyUnicode_AsKind(str1, rkind);
10608 if (!buf1) goto error;
10609 release1 = 1;
10610 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010611 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010612 if (n == 0)
10613 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010614 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010615 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010616 buf2 = _PyUnicode_AsKind(str2, rkind);
10617 if (!buf2) goto error;
10618 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010620 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010621 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010622 rkind = kind2;
10623 sbuf = _PyUnicode_AsKind(self, rkind);
10624 if (!sbuf) goto error;
10625 srelease = 1;
10626 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010627 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 buf1 = _PyUnicode_AsKind(str1, rkind);
10629 if (!buf1) goto error;
10630 release1 = 1;
10631 }
10632 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10633 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010634 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 PyErr_SetString(PyExc_OverflowError,
10636 "replace string is too long");
10637 goto error;
10638 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010639 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010640 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010641 _Py_INCREF_UNICODE_EMPTY();
10642 if (!unicode_empty)
10643 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010644 u = unicode_empty;
10645 goto done;
10646 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010647 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010648 PyErr_SetString(PyExc_OverflowError,
10649 "replace string is too long");
10650 goto error;
10651 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010652 u = PyUnicode_New(new_size, maxchar);
10653 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010654 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010655 assert(PyUnicode_KIND(u) == rkind);
10656 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010657 ires = i = 0;
10658 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010659 while (n-- > 0) {
10660 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010661 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010662 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010663 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010664 if (j == -1)
10665 break;
10666 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010667 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010668 memcpy(res + rkind * ires,
10669 sbuf + rkind * i,
10670 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010671 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010672 }
10673 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010674 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010675 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010677 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010679 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010681 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010682 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010683 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010684 memcpy(res + rkind * ires,
10685 sbuf + rkind * i,
10686 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010687 }
10688 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010689 /* interleave */
10690 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010691 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010692 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010693 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010694 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010695 if (--n <= 0)
10696 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010697 memcpy(res + rkind * ires,
10698 sbuf + rkind * i,
10699 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 ires++;
10701 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010702 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010703 memcpy(res + rkind * ires,
10704 sbuf + rkind * i,
10705 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010706 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010707 }
10708
10709 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010710 unicode_adjust_maxchar(&u);
10711 if (u == NULL)
10712 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010713 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010714
10715 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010716 if (srelease)
10717 PyMem_FREE(sbuf);
10718 if (release1)
10719 PyMem_FREE(buf1);
10720 if (release2)
10721 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010722 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010723 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010724
Benjamin Peterson29060642009-01-31 22:14:21 +000010725 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010726 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010727 if (srelease)
10728 PyMem_FREE(sbuf);
10729 if (release1)
10730 PyMem_FREE(buf1);
10731 if (release2)
10732 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010733 return unicode_result_unchanged(self);
10734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 error:
10736 if (srelease && sbuf)
10737 PyMem_FREE(sbuf);
10738 if (release1 && buf1)
10739 PyMem_FREE(buf1);
10740 if (release2 && buf2)
10741 PyMem_FREE(buf2);
10742 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010743}
10744
10745/* --- Unicode Object Methods --------------------------------------------- */
10746
INADA Naoki3ae20562017-01-16 20:41:20 +090010747/*[clinic input]
10748str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010749
INADA Naoki3ae20562017-01-16 20:41:20 +090010750Return a version of the string where each word is titlecased.
10751
10752More specifically, words start with uppercased characters and all remaining
10753cased characters have lower case.
10754[clinic start generated code]*/
10755
10756static PyObject *
10757unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010758/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010759{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010760 if (PyUnicode_READY(self) == -1)
10761 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010762 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763}
10764
INADA Naoki3ae20562017-01-16 20:41:20 +090010765/*[clinic input]
10766str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767
INADA Naoki3ae20562017-01-16 20:41:20 +090010768Return a capitalized version of the string.
10769
10770More specifically, make the first character have upper case and the rest lower
10771case.
10772[clinic start generated code]*/
10773
10774static PyObject *
10775unicode_capitalize_impl(PyObject *self)
10776/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010777{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010778 if (PyUnicode_READY(self) == -1)
10779 return NULL;
10780 if (PyUnicode_GET_LENGTH(self) == 0)
10781 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010782 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783}
10784
INADA Naoki3ae20562017-01-16 20:41:20 +090010785/*[clinic input]
10786str.casefold as unicode_casefold
10787
10788Return a version of the string suitable for caseless comparisons.
10789[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010790
10791static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010792unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010793/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010794{
10795 if (PyUnicode_READY(self) == -1)
10796 return NULL;
10797 if (PyUnicode_IS_ASCII(self))
10798 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010799 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010800}
10801
10802
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010803/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010804
10805static int
10806convert_uc(PyObject *obj, void *addr)
10807{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010808 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010809
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010810 if (!PyUnicode_Check(obj)) {
10811 PyErr_Format(PyExc_TypeError,
10812 "The fill character must be a unicode character, "
Victor Stinner998b8062018-09-12 00:23:25 +020010813 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010814 return 0;
10815 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010816 if (PyUnicode_READY(obj) < 0)
10817 return 0;
10818 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010819 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010820 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010821 return 0;
10822 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010823 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010824 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010825}
10826
INADA Naoki3ae20562017-01-16 20:41:20 +090010827/*[clinic input]
10828str.center as unicode_center
10829
10830 width: Py_ssize_t
10831 fillchar: Py_UCS4 = ' '
10832 /
10833
10834Return a centered string of length width.
10835
10836Padding is done using the specified fill character (default is a space).
10837[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838
10839static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010840unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10841/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010843 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010844
Benjamin Petersonbac79492012-01-14 13:34:47 -050010845 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010846 return NULL;
10847
Victor Stinnerc4b49542011-12-11 22:44:26 +010010848 if (PyUnicode_GET_LENGTH(self) >= width)
10849 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010850
Victor Stinnerc4b49542011-12-11 22:44:26 +010010851 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852 left = marg / 2 + (marg & width & 1);
10853
Victor Stinner9310abb2011-10-05 00:59:23 +020010854 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010855}
10856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010857/* This function assumes that str1 and str2 are readied by the caller. */
10858
Marc-André Lemburge5034372000-08-08 08:04:29 +000010859static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010860unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010861{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010862#define COMPARE(TYPE1, TYPE2) \
10863 do { \
10864 TYPE1* p1 = (TYPE1 *)data1; \
10865 TYPE2* p2 = (TYPE2 *)data2; \
10866 TYPE1* end = p1 + len; \
10867 Py_UCS4 c1, c2; \
10868 for (; p1 != end; p1++, p2++) { \
10869 c1 = *p1; \
10870 c2 = *p2; \
10871 if (c1 != c2) \
10872 return (c1 < c2) ? -1 : 1; \
10873 } \
10874 } \
10875 while (0)
10876
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010877 int kind1, kind2;
10878 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010879 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010880
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010881 kind1 = PyUnicode_KIND(str1);
10882 kind2 = PyUnicode_KIND(str2);
10883 data1 = PyUnicode_DATA(str1);
10884 data2 = PyUnicode_DATA(str2);
10885 len1 = PyUnicode_GET_LENGTH(str1);
10886 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010887 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010888
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010889 switch(kind1) {
10890 case PyUnicode_1BYTE_KIND:
10891 {
10892 switch(kind2) {
10893 case PyUnicode_1BYTE_KIND:
10894 {
10895 int cmp = memcmp(data1, data2, len);
10896 /* normalize result of memcmp() into the range [-1; 1] */
10897 if (cmp < 0)
10898 return -1;
10899 if (cmp > 0)
10900 return 1;
10901 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010902 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010903 case PyUnicode_2BYTE_KIND:
10904 COMPARE(Py_UCS1, Py_UCS2);
10905 break;
10906 case PyUnicode_4BYTE_KIND:
10907 COMPARE(Py_UCS1, Py_UCS4);
10908 break;
10909 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010910 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010911 }
10912 break;
10913 }
10914 case PyUnicode_2BYTE_KIND:
10915 {
10916 switch(kind2) {
10917 case PyUnicode_1BYTE_KIND:
10918 COMPARE(Py_UCS2, Py_UCS1);
10919 break;
10920 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010921 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010922 COMPARE(Py_UCS2, Py_UCS2);
10923 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010924 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010925 case PyUnicode_4BYTE_KIND:
10926 COMPARE(Py_UCS2, Py_UCS4);
10927 break;
10928 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010929 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010930 }
10931 break;
10932 }
10933 case PyUnicode_4BYTE_KIND:
10934 {
10935 switch(kind2) {
10936 case PyUnicode_1BYTE_KIND:
10937 COMPARE(Py_UCS4, Py_UCS1);
10938 break;
10939 case PyUnicode_2BYTE_KIND:
10940 COMPARE(Py_UCS4, Py_UCS2);
10941 break;
10942 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010943 {
10944#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10945 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10946 /* normalize result of wmemcmp() into the range [-1; 1] */
10947 if (cmp < 0)
10948 return -1;
10949 if (cmp > 0)
10950 return 1;
10951#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010952 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010953#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010954 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010955 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010956 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010957 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010958 }
10959 break;
10960 }
10961 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010962 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010963 }
10964
Victor Stinner770e19e2012-10-04 22:59:45 +020010965 if (len1 == len2)
10966 return 0;
10967 if (len1 < len2)
10968 return -1;
10969 else
10970 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010971
10972#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010973}
10974
Benjamin Peterson621b4302016-09-09 13:54:34 -070010975static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010976unicode_compare_eq(PyObject *str1, PyObject *str2)
10977{
10978 int kind;
10979 void *data1, *data2;
10980 Py_ssize_t len;
10981 int cmp;
10982
Victor Stinnere5567ad2012-10-23 02:48:49 +020010983 len = PyUnicode_GET_LENGTH(str1);
10984 if (PyUnicode_GET_LENGTH(str2) != len)
10985 return 0;
10986 kind = PyUnicode_KIND(str1);
10987 if (PyUnicode_KIND(str2) != kind)
10988 return 0;
10989 data1 = PyUnicode_DATA(str1);
10990 data2 = PyUnicode_DATA(str2);
10991
10992 cmp = memcmp(data1, data2, len * kind);
10993 return (cmp == 0);
10994}
10995
10996
Alexander Belopolsky40018472011-02-26 01:02:56 +000010997int
10998PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011000 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11001 if (PyUnicode_READY(left) == -1 ||
11002 PyUnicode_READY(right) == -1)
11003 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011004
11005 /* a string is equal to itself */
11006 if (left == right)
11007 return 0;
11008
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011009 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011010 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011011 PyErr_Format(PyExc_TypeError,
11012 "Can't compare %.100s and %.100s",
11013 left->ob_type->tp_name,
11014 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015 return -1;
11016}
11017
Martin v. Löwis5b222132007-06-10 09:51:05 +000011018int
11019PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11020{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011021 Py_ssize_t i;
11022 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011023 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011024 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011025
Victor Stinner910337b2011-10-03 03:20:16 +020011026 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011027 if (!PyUnicode_IS_READY(uni)) {
11028 const wchar_t *ws = _PyUnicode_WSTR(uni);
11029 /* Compare Unicode string and source character set string */
11030 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11031 if (chr != ustr[i])
11032 return (chr < ustr[i]) ? -1 : 1;
11033 }
11034 /* This check keeps Python strings that end in '\0' from comparing equal
11035 to C strings identical up to that point. */
11036 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11037 return 1; /* uni is longer */
11038 if (ustr[i])
11039 return -1; /* str is longer */
11040 return 0;
11041 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011042 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011043 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011044 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011045 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011046 size_t len, len2 = strlen(str);
11047 int cmp;
11048
11049 len = Py_MIN(len1, len2);
11050 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011051 if (cmp != 0) {
11052 if (cmp < 0)
11053 return -1;
11054 else
11055 return 1;
11056 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011057 if (len1 > len2)
11058 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011059 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011060 return -1; /* str is longer */
11061 return 0;
11062 }
11063 else {
11064 void *data = PyUnicode_DATA(uni);
11065 /* Compare Unicode string and source character set string */
11066 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011067 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011068 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11069 /* This check keeps Python strings that end in '\0' from comparing equal
11070 to C strings identical up to that point. */
11071 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11072 return 1; /* uni is longer */
11073 if (str[i])
11074 return -1; /* str is longer */
11075 return 0;
11076 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011077}
11078
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011079static int
11080non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11081{
11082 size_t i, len;
11083 const wchar_t *p;
11084 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11085 if (strlen(str) != len)
11086 return 0;
11087 p = _PyUnicode_WSTR(unicode);
11088 assert(p);
11089 for (i = 0; i < len; i++) {
11090 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011091 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011092 return 0;
11093 }
11094 return 1;
11095}
11096
11097int
11098_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11099{
11100 size_t len;
11101 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011102 assert(str);
11103#ifndef NDEBUG
11104 for (const char *p = str; *p; p++) {
11105 assert((unsigned char)*p < 128);
11106 }
11107#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011108 if (PyUnicode_READY(unicode) == -1) {
11109 /* Memory error or bad data */
11110 PyErr_Clear();
11111 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11112 }
11113 if (!PyUnicode_IS_ASCII(unicode))
11114 return 0;
11115 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11116 return strlen(str) == len &&
11117 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11118}
11119
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011120int
11121_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11122{
11123 PyObject *right_uni;
11124 Py_hash_t hash;
11125
11126 assert(_PyUnicode_CHECK(left));
11127 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011128#ifndef NDEBUG
11129 for (const char *p = right->string; *p; p++) {
11130 assert((unsigned char)*p < 128);
11131 }
11132#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011133
11134 if (PyUnicode_READY(left) == -1) {
11135 /* memory error or bad data */
11136 PyErr_Clear();
11137 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11138 }
11139
11140 if (!PyUnicode_IS_ASCII(left))
11141 return 0;
11142
11143 right_uni = _PyUnicode_FromId(right); /* borrowed */
11144 if (right_uni == NULL) {
11145 /* memory error or bad data */
11146 PyErr_Clear();
11147 return _PyUnicode_EqualToASCIIString(left, right->string);
11148 }
11149
11150 if (left == right_uni)
11151 return 1;
11152
11153 if (PyUnicode_CHECK_INTERNED(left))
11154 return 0;
11155
INADA Naoki7cc95f52018-01-28 02:07:09 +090011156 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011157 hash = _PyUnicode_HASH(left);
11158 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11159 return 0;
11160
11161 return unicode_compare_eq(left, right_uni);
11162}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011163
Alexander Belopolsky40018472011-02-26 01:02:56 +000011164PyObject *
11165PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011166{
11167 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011168
Victor Stinnere5567ad2012-10-23 02:48:49 +020011169 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11170 Py_RETURN_NOTIMPLEMENTED;
11171
11172 if (PyUnicode_READY(left) == -1 ||
11173 PyUnicode_READY(right) == -1)
11174 return NULL;
11175
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011176 if (left == right) {
11177 switch (op) {
11178 case Py_EQ:
11179 case Py_LE:
11180 case Py_GE:
11181 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011182 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011183 case Py_NE:
11184 case Py_LT:
11185 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011186 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011187 default:
11188 PyErr_BadArgument();
11189 return NULL;
11190 }
11191 }
11192 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011193 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011194 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011195 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011196 }
11197 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011198 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011199 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011200 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011201}
11202
Alexander Belopolsky40018472011-02-26 01:02:56 +000011203int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011204_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11205{
11206 return unicode_eq(aa, bb);
11207}
11208
11209int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011210PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011211{
Victor Stinner77282cb2013-04-14 19:22:47 +020011212 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011213 void *buf1, *buf2;
11214 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011215 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011216
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011217 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011218 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020011219 "'in <string>' requires string as left operand, not %.100s",
11220 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011221 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011222 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011223 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011224 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011225 if (ensure_unicode(str) < 0)
11226 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011229 kind2 = PyUnicode_KIND(substr);
11230 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011231 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011233 len2 = PyUnicode_GET_LENGTH(substr);
11234 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011235 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011236 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011237 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011238 if (len2 == 1) {
11239 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11240 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011241 return result;
11242 }
11243 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011244 buf2 = _PyUnicode_AsKind(substr, kind1);
11245 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011246 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011247 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011248
Victor Stinner77282cb2013-04-14 19:22:47 +020011249 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011250 case PyUnicode_1BYTE_KIND:
11251 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11252 break;
11253 case PyUnicode_2BYTE_KIND:
11254 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11255 break;
11256 case PyUnicode_4BYTE_KIND:
11257 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11258 break;
11259 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011260 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011261 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011262
Victor Stinner77282cb2013-04-14 19:22:47 +020011263 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011264 PyMem_Free(buf2);
11265
Guido van Rossum403d68b2000-03-13 15:55:09 +000011266 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011267}
11268
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269/* Concat to string or Unicode object giving a new Unicode object. */
11270
Alexander Belopolsky40018472011-02-26 01:02:56 +000011271PyObject *
11272PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011274 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011275 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011276 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011278 if (ensure_unicode(left) < 0)
11279 return NULL;
11280
11281 if (!PyUnicode_Check(right)) {
11282 PyErr_Format(PyExc_TypeError,
11283 "can only concatenate str (not \"%.200s\") to str",
11284 right->ob_type->tp_name);
11285 return NULL;
11286 }
11287 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011288 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011289
11290 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011291 if (left == unicode_empty)
11292 return PyUnicode_FromObject(right);
11293 if (right == unicode_empty)
11294 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011296 left_len = PyUnicode_GET_LENGTH(left);
11297 right_len = PyUnicode_GET_LENGTH(right);
11298 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011299 PyErr_SetString(PyExc_OverflowError,
11300 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011301 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011302 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011303 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011304
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011305 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11306 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011307 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011310 result = PyUnicode_New(new_len, maxchar);
11311 if (result == NULL)
11312 return NULL;
11313 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11314 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11315 assert(_PyUnicode_CheckConsistency(result, 1));
11316 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011317}
11318
Walter Dörwald1ab83302007-05-18 17:15:44 +000011319void
Victor Stinner23e56682011-10-03 03:54:37 +020011320PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011321{
Victor Stinner23e56682011-10-03 03:54:37 +020011322 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011323 Py_UCS4 maxchar, maxchar2;
11324 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011325
11326 if (p_left == NULL) {
11327 if (!PyErr_Occurred())
11328 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011329 return;
11330 }
Victor Stinner23e56682011-10-03 03:54:37 +020011331 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011332 if (right == NULL || left == NULL
11333 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011334 if (!PyErr_Occurred())
11335 PyErr_BadInternalCall();
11336 goto error;
11337 }
11338
Benjamin Petersonbac79492012-01-14 13:34:47 -050011339 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011340 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011341 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011342 goto error;
11343
Victor Stinner488fa492011-12-12 00:01:39 +010011344 /* Shortcuts */
11345 if (left == unicode_empty) {
11346 Py_DECREF(left);
11347 Py_INCREF(right);
11348 *p_left = right;
11349 return;
11350 }
11351 if (right == unicode_empty)
11352 return;
11353
11354 left_len = PyUnicode_GET_LENGTH(left);
11355 right_len = PyUnicode_GET_LENGTH(right);
11356 if (left_len > PY_SSIZE_T_MAX - right_len) {
11357 PyErr_SetString(PyExc_OverflowError,
11358 "strings are too large to concat");
11359 goto error;
11360 }
11361 new_len = left_len + right_len;
11362
11363 if (unicode_modifiable(left)
11364 && PyUnicode_CheckExact(right)
11365 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011366 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11367 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011368 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011369 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011370 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11371 {
11372 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011373 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011374 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011375
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011376 /* copy 'right' into the newly allocated area of 'left' */
11377 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011378 }
Victor Stinner488fa492011-12-12 00:01:39 +010011379 else {
11380 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11381 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011382 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011383
Victor Stinner488fa492011-12-12 00:01:39 +010011384 /* Concat the two Unicode strings */
11385 res = PyUnicode_New(new_len, maxchar);
11386 if (res == NULL)
11387 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011388 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11389 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011390 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011391 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011392 }
11393 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011394 return;
11395
11396error:
Victor Stinner488fa492011-12-12 00:01:39 +010011397 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011398}
11399
11400void
11401PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11402{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011403 PyUnicode_Append(pleft, right);
11404 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011405}
11406
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011407/*
11408Wraps stringlib_parse_args_finds() and additionally ensures that the
11409first argument is a unicode object.
11410*/
11411
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011412static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011413parse_args_finds_unicode(const char * function_name, PyObject *args,
11414 PyObject **substring,
11415 Py_ssize_t *start, Py_ssize_t *end)
11416{
11417 if(stringlib_parse_args_finds(function_name, args, substring,
11418 start, end)) {
11419 if (ensure_unicode(*substring) < 0)
11420 return 0;
11421 return 1;
11422 }
11423 return 0;
11424}
11425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011426PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011427 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011429Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011430string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011431interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432
11433static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011434unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011436 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011437 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011438 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011440 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 void *buf1, *buf2;
11442 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011443
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011444 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 kind1 = PyUnicode_KIND(self);
11448 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011449 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011450 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 len1 = PyUnicode_GET_LENGTH(self);
11453 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011455 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011456 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011457
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011458 buf1 = PyUnicode_DATA(self);
11459 buf2 = PyUnicode_DATA(substring);
11460 if (kind2 != kind1) {
11461 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011462 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011463 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011464 }
11465 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 case PyUnicode_1BYTE_KIND:
11467 iresult = ucs1lib_count(
11468 ((Py_UCS1*)buf1) + start, end - start,
11469 buf2, len2, PY_SSIZE_T_MAX
11470 );
11471 break;
11472 case PyUnicode_2BYTE_KIND:
11473 iresult = ucs2lib_count(
11474 ((Py_UCS2*)buf1) + start, end - start,
11475 buf2, len2, PY_SSIZE_T_MAX
11476 );
11477 break;
11478 case PyUnicode_4BYTE_KIND:
11479 iresult = ucs4lib_count(
11480 ((Py_UCS4*)buf1) + start, end - start,
11481 buf2, len2, PY_SSIZE_T_MAX
11482 );
11483 break;
11484 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011485 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011486 }
11487
11488 result = PyLong_FromSsize_t(iresult);
11489
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011490 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011491 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493 return result;
11494}
11495
INADA Naoki3ae20562017-01-16 20:41:20 +090011496/*[clinic input]
11497str.encode as unicode_encode
11498
11499 encoding: str(c_default="NULL") = 'utf-8'
11500 The encoding in which to encode the string.
11501 errors: str(c_default="NULL") = 'strict'
11502 The error handling scheme to use for encoding errors.
11503 The default is 'strict' meaning that encoding errors raise a
11504 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11505 'xmlcharrefreplace' as well as any other name registered with
11506 codecs.register_error that can handle UnicodeEncodeErrors.
11507
11508Encode the string using the codec registered for encoding.
11509[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
11511static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011512unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011513/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011515 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011516}
11517
INADA Naoki3ae20562017-01-16 20:41:20 +090011518/*[clinic input]
11519str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520
INADA Naoki3ae20562017-01-16 20:41:20 +090011521 tabsize: int = 8
11522
11523Return a copy where all tab characters are expanded using spaces.
11524
11525If tabsize is not given, a tab size of 8 characters is assumed.
11526[clinic start generated code]*/
11527
11528static PyObject *
11529unicode_expandtabs_impl(PyObject *self, int tabsize)
11530/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011531{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011532 Py_ssize_t i, j, line_pos, src_len, incr;
11533 Py_UCS4 ch;
11534 PyObject *u;
11535 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011536 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011537 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538
Antoine Pitrou22425222011-10-04 19:10:51 +020011539 if (PyUnicode_READY(self) == -1)
11540 return NULL;
11541
Thomas Wouters7e474022000-07-16 12:04:32 +000011542 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011543 src_len = PyUnicode_GET_LENGTH(self);
11544 i = j = line_pos = 0;
11545 kind = PyUnicode_KIND(self);
11546 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011547 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011548 for (; i < src_len; i++) {
11549 ch = PyUnicode_READ(kind, src_data, i);
11550 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011551 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011553 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011554 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011555 goto overflow;
11556 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011557 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011558 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011559 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011561 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011562 goto overflow;
11563 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011565 if (ch == '\n' || ch == '\r')
11566 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011568 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011569 if (!found)
11570 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011571
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011573 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574 if (!u)
11575 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011576 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011577
Antoine Pitroue71d5742011-10-04 15:55:09 +020011578 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579
Antoine Pitroue71d5742011-10-04 15:55:09 +020011580 for (; i < src_len; i++) {
11581 ch = PyUnicode_READ(kind, src_data, i);
11582 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011583 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011584 incr = tabsize - (line_pos % tabsize);
11585 line_pos += incr;
Victor Stinner59423e32018-11-26 13:40:01 +010011586 unicode_fill(kind, dest_data, ' ', j, incr);
Victor Stinnerda79e632012-02-22 13:37:04 +010011587 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011588 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011589 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011590 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011591 line_pos++;
11592 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011593 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011594 if (ch == '\n' || ch == '\r')
11595 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011597 }
11598 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011599 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011600
Antoine Pitroue71d5742011-10-04 15:55:09 +020011601 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011602 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11603 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604}
11605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011606PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608\n\
11609Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011610such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611arguments start and end are interpreted as in slice notation.\n\
11612\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011613Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614
11615static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011618 /* initialize variables to prevent gcc warning */
11619 PyObject *substring = NULL;
11620 Py_ssize_t start = 0;
11621 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011622 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011624 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011627 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011630 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 if (result == -2)
11633 return NULL;
11634
Christian Heimes217cfd12007-12-02 14:31:20 +000011635 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011636}
11637
11638static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011639unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011640{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011641 void *data;
11642 enum PyUnicode_Kind kind;
11643 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011644
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011645 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011646 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011648 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011649 if (PyUnicode_READY(self) == -1) {
11650 return NULL;
11651 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011652 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11653 PyErr_SetString(PyExc_IndexError, "string index out of range");
11654 return NULL;
11655 }
11656 kind = PyUnicode_KIND(self);
11657 data = PyUnicode_DATA(self);
11658 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011659 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011660}
11661
Guido van Rossumc2504932007-09-18 19:42:40 +000011662/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011663 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011664static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011665unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011666{
Guido van Rossumc2504932007-09-18 19:42:40 +000011667 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011668 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011669
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011670#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011671 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011672#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673 if (_PyUnicode_HASH(self) != -1)
11674 return _PyUnicode_HASH(self);
11675 if (PyUnicode_READY(self) == -1)
11676 return -1;
11677 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011678 /*
11679 We make the hash of the empty string be 0, rather than using
11680 (prefix ^ suffix), since this slightly obfuscates the hash secret
11681 */
11682 if (len == 0) {
11683 _PyUnicode_HASH(self) = 0;
11684 return 0;
11685 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011686 x = _Py_HashBytes(PyUnicode_DATA(self),
11687 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011689 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690}
11691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011692PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011693 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694\n\
oldkaa0735f2018-02-02 16:52:55 +080011695Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011696such that sub is contained within S[start:end]. Optional\n\
11697arguments start and end are interpreted as in slice notation.\n\
11698\n\
11699Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700
11701static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011702unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011704 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011705 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011706 PyObject *substring = NULL;
11707 Py_ssize_t start = 0;
11708 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011710 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011713 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011716 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011717
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718 if (result == -2)
11719 return NULL;
11720
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 if (result < 0) {
11722 PyErr_SetString(PyExc_ValueError, "substring not found");
11723 return NULL;
11724 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011725
Christian Heimes217cfd12007-12-02 14:31:20 +000011726 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727}
11728
INADA Naoki3ae20562017-01-16 20:41:20 +090011729/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011730str.isascii as unicode_isascii
11731
11732Return True if all characters in the string are ASCII, False otherwise.
11733
11734ASCII characters have code points in the range U+0000-U+007F.
11735Empty string is ASCII too.
11736[clinic start generated code]*/
11737
11738static PyObject *
11739unicode_isascii_impl(PyObject *self)
11740/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11741{
11742 if (PyUnicode_READY(self) == -1) {
11743 return NULL;
11744 }
11745 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11746}
11747
11748/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011749str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750
INADA Naoki3ae20562017-01-16 20:41:20 +090011751Return True if the string is a lowercase string, False otherwise.
11752
11753A string is lowercase if all cased characters in the string are lowercase and
11754there is at least one cased character in the string.
11755[clinic start generated code]*/
11756
11757static PyObject *
11758unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011759/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011760{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011761 Py_ssize_t i, length;
11762 int kind;
11763 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011764 int cased;
11765
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011766 if (PyUnicode_READY(self) == -1)
11767 return NULL;
11768 length = PyUnicode_GET_LENGTH(self);
11769 kind = PyUnicode_KIND(self);
11770 data = PyUnicode_DATA(self);
11771
Guido van Rossumd57fd912000-03-10 22:53:23 +000011772 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011773 if (length == 1)
11774 return PyBool_FromLong(
11775 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011777 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011779 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011780
Guido van Rossumd57fd912000-03-10 22:53:23 +000011781 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011782 for (i = 0; i < length; i++) {
11783 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011784
Benjamin Peterson29060642009-01-31 22:14:21 +000011785 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011786 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011787 else if (!cased && Py_UNICODE_ISLOWER(ch))
11788 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011790 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011791}
11792
INADA Naoki3ae20562017-01-16 20:41:20 +090011793/*[clinic input]
11794str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011795
INADA Naoki3ae20562017-01-16 20:41:20 +090011796Return True if the string is an uppercase string, False otherwise.
11797
11798A string is uppercase if all cased characters in the string are uppercase and
11799there is at least one cased character in the string.
11800[clinic start generated code]*/
11801
11802static PyObject *
11803unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011804/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 Py_ssize_t i, length;
11807 int kind;
11808 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011809 int cased;
11810
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 if (PyUnicode_READY(self) == -1)
11812 return NULL;
11813 length = PyUnicode_GET_LENGTH(self);
11814 kind = PyUnicode_KIND(self);
11815 data = PyUnicode_DATA(self);
11816
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 if (length == 1)
11819 return PyBool_FromLong(
11820 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011821
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011822 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011824 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011825
Guido van Rossumd57fd912000-03-10 22:53:23 +000011826 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 for (i = 0; i < length; i++) {
11828 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011829
Benjamin Peterson29060642009-01-31 22:14:21 +000011830 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011831 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011832 else if (!cased && Py_UNICODE_ISUPPER(ch))
11833 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011835 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011836}
11837
INADA Naoki3ae20562017-01-16 20:41:20 +090011838/*[clinic input]
11839str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840
INADA Naoki3ae20562017-01-16 20:41:20 +090011841Return True if the string is a title-cased string, False otherwise.
11842
11843In a title-cased string, upper- and title-case characters may only
11844follow uncased characters and lowercase characters only cased ones.
11845[clinic start generated code]*/
11846
11847static PyObject *
11848unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011849/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011850{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 Py_ssize_t i, length;
11852 int kind;
11853 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011854 int cased, previous_is_cased;
11855
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011856 if (PyUnicode_READY(self) == -1)
11857 return NULL;
11858 length = PyUnicode_GET_LENGTH(self);
11859 kind = PyUnicode_KIND(self);
11860 data = PyUnicode_DATA(self);
11861
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011863 if (length == 1) {
11864 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11865 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11866 (Py_UNICODE_ISUPPER(ch) != 0));
11867 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011869 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011870 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011871 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011872
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873 cased = 0;
11874 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 for (i = 0; i < length; i++) {
11876 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011877
Benjamin Peterson29060642009-01-31 22:14:21 +000011878 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11879 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011880 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011881 previous_is_cased = 1;
11882 cased = 1;
11883 }
11884 else if (Py_UNICODE_ISLOWER(ch)) {
11885 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011886 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011887 previous_is_cased = 1;
11888 cased = 1;
11889 }
11890 else
11891 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011892 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011893 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894}
11895
INADA Naoki3ae20562017-01-16 20:41:20 +090011896/*[clinic input]
11897str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011898
INADA Naoki3ae20562017-01-16 20:41:20 +090011899Return True if the string is a whitespace string, False otherwise.
11900
11901A string is whitespace if all characters in the string are whitespace and there
11902is at least one character in the string.
11903[clinic start generated code]*/
11904
11905static PyObject *
11906unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011907/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011908{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 Py_ssize_t i, length;
11910 int kind;
11911 void *data;
11912
11913 if (PyUnicode_READY(self) == -1)
11914 return NULL;
11915 length = PyUnicode_GET_LENGTH(self);
11916 kind = PyUnicode_KIND(self);
11917 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011920 if (length == 1)
11921 return PyBool_FromLong(
11922 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011923
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011924 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011926 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011927
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 for (i = 0; i < length; i++) {
11929 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011930 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011931 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011932 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011933 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934}
11935
INADA Naoki3ae20562017-01-16 20:41:20 +090011936/*[clinic input]
11937str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011938
INADA Naoki3ae20562017-01-16 20:41:20 +090011939Return True if the string is an alphabetic string, False otherwise.
11940
11941A string is alphabetic if all characters in the string are alphabetic and there
11942is at least one character in the string.
11943[clinic start generated code]*/
11944
11945static PyObject *
11946unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011947/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011948{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011949 Py_ssize_t i, length;
11950 int kind;
11951 void *data;
11952
11953 if (PyUnicode_READY(self) == -1)
11954 return NULL;
11955 length = PyUnicode_GET_LENGTH(self);
11956 kind = PyUnicode_KIND(self);
11957 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011958
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011959 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 if (length == 1)
11961 return PyBool_FromLong(
11962 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011963
11964 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011965 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011966 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011967
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 for (i = 0; i < length; i++) {
11969 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011970 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011971 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011972 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011973}
11974
INADA Naoki3ae20562017-01-16 20:41:20 +090011975/*[clinic input]
11976str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011977
INADA Naoki3ae20562017-01-16 20:41:20 +090011978Return True if the string is an alpha-numeric string, False otherwise.
11979
11980A string is alpha-numeric if all characters in the string are alpha-numeric and
11981there is at least one character in the string.
11982[clinic start generated code]*/
11983
11984static PyObject *
11985unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011986/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011987{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 int kind;
11989 void *data;
11990 Py_ssize_t len, i;
11991
11992 if (PyUnicode_READY(self) == -1)
11993 return NULL;
11994
11995 kind = PyUnicode_KIND(self);
11996 data = PyUnicode_DATA(self);
11997 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011998
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011999 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012000 if (len == 1) {
12001 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12002 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12003 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012004
12005 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012006 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012007 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012008
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012009 for (i = 0; i < len; i++) {
12010 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012011 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012012 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012013 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012014 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012015}
12016
INADA Naoki3ae20562017-01-16 20:41:20 +090012017/*[clinic input]
12018str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000012019
INADA Naoki3ae20562017-01-16 20:41:20 +090012020Return True if the string is a decimal string, False otherwise.
12021
12022A string is a decimal string if all characters in the string are decimal and
12023there is at least one character in the string.
12024[clinic start generated code]*/
12025
12026static PyObject *
12027unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012028/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012029{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030 Py_ssize_t i, length;
12031 int kind;
12032 void *data;
12033
12034 if (PyUnicode_READY(self) == -1)
12035 return NULL;
12036 length = PyUnicode_GET_LENGTH(self);
12037 kind = PyUnicode_KIND(self);
12038 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012039
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012041 if (length == 1)
12042 return PyBool_FromLong(
12043 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012044
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012045 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012047 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 for (i = 0; i < length; i++) {
12050 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012051 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012052 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012053 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054}
12055
INADA Naoki3ae20562017-01-16 20:41:20 +090012056/*[clinic input]
12057str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000012058
INADA Naoki3ae20562017-01-16 20:41:20 +090012059Return True if the string is a digit string, False otherwise.
12060
12061A string is a digit string if all characters in the string are digits and there
12062is at least one character in the string.
12063[clinic start generated code]*/
12064
12065static PyObject *
12066unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012067/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012068{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 Py_ssize_t i, length;
12070 int kind;
12071 void *data;
12072
12073 if (PyUnicode_READY(self) == -1)
12074 return NULL;
12075 length = PyUnicode_GET_LENGTH(self);
12076 kind = PyUnicode_KIND(self);
12077 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012078
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 if (length == 1) {
12081 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12082 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12083 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012085 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012086 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012087 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 for (i = 0; i < length; i++) {
12090 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012091 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012093 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012094}
12095
INADA Naoki3ae20562017-01-16 20:41:20 +090012096/*[clinic input]
12097str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012098
INADA Naoki3ae20562017-01-16 20:41:20 +090012099Return True if the string is a numeric string, False otherwise.
12100
12101A string is numeric if all characters in the string are numeric and there is at
12102least one character in the string.
12103[clinic start generated code]*/
12104
12105static PyObject *
12106unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012107/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012108{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012109 Py_ssize_t i, length;
12110 int kind;
12111 void *data;
12112
12113 if (PyUnicode_READY(self) == -1)
12114 return NULL;
12115 length = PyUnicode_GET_LENGTH(self);
12116 kind = PyUnicode_KIND(self);
12117 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012120 if (length == 1)
12121 return PyBool_FromLong(
12122 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012123
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012124 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012126 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012127
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 for (i = 0; i < length; i++) {
12129 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012130 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012132 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012133}
12134
Martin v. Löwis47383402007-08-15 07:32:56 +000012135int
12136PyUnicode_IsIdentifier(PyObject *self)
12137{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012138 int kind;
12139 void *data;
12140 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012141 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012142
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143 if (PyUnicode_READY(self) == -1) {
12144 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012145 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 }
12147
12148 /* Special case for empty strings */
12149 if (PyUnicode_GET_LENGTH(self) == 0)
12150 return 0;
12151 kind = PyUnicode_KIND(self);
12152 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012153
12154 /* PEP 3131 says that the first character must be in
12155 XID_Start and subsequent characters in XID_Continue,
12156 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012157 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012158 letters, digits, underscore). However, given the current
12159 definition of XID_Start and XID_Continue, it is sufficient
12160 to check just for these, except that _ must be allowed
12161 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012163 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012164 return 0;
12165
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012166 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012167 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012168 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012169 return 1;
12170}
12171
INADA Naoki3ae20562017-01-16 20:41:20 +090012172/*[clinic input]
12173str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012174
INADA Naoki3ae20562017-01-16 20:41:20 +090012175Return True if the string is a valid Python identifier, False otherwise.
12176
Sanyam Khuranaffc5a142018-10-08 12:23:32 +053012177Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012178such as "def" or "class".
INADA Naoki3ae20562017-01-16 20:41:20 +090012179[clinic start generated code]*/
12180
12181static PyObject *
12182unicode_isidentifier_impl(PyObject *self)
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012183/*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012184{
12185 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12186}
12187
INADA Naoki3ae20562017-01-16 20:41:20 +090012188/*[clinic input]
12189str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012190
INADA Naoki3ae20562017-01-16 20:41:20 +090012191Return True if the string is printable, False otherwise.
12192
12193A string is printable if all of its characters are considered printable in
12194repr() or if it is empty.
12195[clinic start generated code]*/
12196
12197static PyObject *
12198unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012199/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012200{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012201 Py_ssize_t i, length;
12202 int kind;
12203 void *data;
12204
12205 if (PyUnicode_READY(self) == -1)
12206 return NULL;
12207 length = PyUnicode_GET_LENGTH(self);
12208 kind = PyUnicode_KIND(self);
12209 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012210
12211 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212 if (length == 1)
12213 return PyBool_FromLong(
12214 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012215
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012216 for (i = 0; i < length; i++) {
12217 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012218 Py_RETURN_FALSE;
12219 }
12220 }
12221 Py_RETURN_TRUE;
12222}
12223
INADA Naoki3ae20562017-01-16 20:41:20 +090012224/*[clinic input]
12225str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012226
INADA Naoki3ae20562017-01-16 20:41:20 +090012227 iterable: object
12228 /
12229
12230Concatenate any number of strings.
12231
Martin Panter91a88662017-01-24 00:30:06 +000012232The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012233The result is returned as a new string.
12234
12235Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12236[clinic start generated code]*/
12237
12238static PyObject *
12239unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012240/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241{
INADA Naoki3ae20562017-01-16 20:41:20 +090012242 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243}
12244
Martin v. Löwis18e16552006-02-15 17:27:45 +000012245static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012246unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 if (PyUnicode_READY(self) == -1)
12249 return -1;
12250 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251}
12252
INADA Naoki3ae20562017-01-16 20:41:20 +090012253/*[clinic input]
12254str.ljust as unicode_ljust
12255
12256 width: Py_ssize_t
12257 fillchar: Py_UCS4 = ' '
12258 /
12259
12260Return a left-justified string of length width.
12261
12262Padding is done using the specified fill character (default is a space).
12263[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264
12265static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012266unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12267/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012269 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012270 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271
Victor Stinnerc4b49542011-12-11 22:44:26 +010012272 if (PyUnicode_GET_LENGTH(self) >= width)
12273 return unicode_result_unchanged(self);
12274
12275 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276}
12277
INADA Naoki3ae20562017-01-16 20:41:20 +090012278/*[clinic input]
12279str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280
INADA Naoki3ae20562017-01-16 20:41:20 +090012281Return a copy of the string converted to lowercase.
12282[clinic start generated code]*/
12283
12284static PyObject *
12285unicode_lower_impl(PyObject *self)
12286/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012288 if (PyUnicode_READY(self) == -1)
12289 return NULL;
12290 if (PyUnicode_IS_ASCII(self))
12291 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012292 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293}
12294
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012295#define LEFTSTRIP 0
12296#define RIGHTSTRIP 1
12297#define BOTHSTRIP 2
12298
12299/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012300static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012301
INADA Naoki3ae20562017-01-16 20:41:20 +090012302#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012303
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012304/* externally visible for str.strip(unicode) */
12305PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012306_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012307{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012308 void *data;
12309 int kind;
12310 Py_ssize_t i, j, len;
12311 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012312 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12315 return NULL;
12316
12317 kind = PyUnicode_KIND(self);
12318 data = PyUnicode_DATA(self);
12319 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012320 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12322 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012323 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012324
Benjamin Peterson14339b62009-01-31 16:36:08 +000012325 i = 0;
12326 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012327 while (i < len) {
12328 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12329 if (!BLOOM(sepmask, ch))
12330 break;
12331 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12332 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012333 i++;
12334 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012335 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012336
Benjamin Peterson14339b62009-01-31 16:36:08 +000012337 j = len;
12338 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012339 j--;
12340 while (j >= i) {
12341 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12342 if (!BLOOM(sepmask, ch))
12343 break;
12344 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12345 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012346 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012347 }
12348
Benjamin Peterson29060642009-01-31 22:14:21 +000012349 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012350 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012351
Victor Stinner7931d9a2011-11-04 00:22:48 +010012352 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012353}
12354
12355PyObject*
12356PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12357{
12358 unsigned char *data;
12359 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012360 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012361
Victor Stinnerde636f32011-10-01 03:55:54 +020012362 if (PyUnicode_READY(self) == -1)
12363 return NULL;
12364
Victor Stinner684d5fd2012-05-03 02:32:34 +020012365 length = PyUnicode_GET_LENGTH(self);
12366 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012367
Victor Stinner684d5fd2012-05-03 02:32:34 +020012368 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012369 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370
Victor Stinnerde636f32011-10-01 03:55:54 +020012371 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012372 PyErr_SetString(PyExc_IndexError, "string index out of range");
12373 return NULL;
12374 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012375 if (start >= length || end < start)
12376 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012377
Victor Stinner684d5fd2012-05-03 02:32:34 +020012378 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012379 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012380 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012381 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012382 }
12383 else {
12384 kind = PyUnicode_KIND(self);
12385 data = PyUnicode_1BYTE_DATA(self);
12386 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012387 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012388 length);
12389 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012390}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391
12392static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012393do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012394{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 Py_ssize_t len, i, j;
12396
12397 if (PyUnicode_READY(self) == -1)
12398 return NULL;
12399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012401
Victor Stinnercc7af722013-04-09 22:39:24 +020012402 if (PyUnicode_IS_ASCII(self)) {
12403 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12404
12405 i = 0;
12406 if (striptype != RIGHTSTRIP) {
12407 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012408 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012409 if (!_Py_ascii_whitespace[ch])
12410 break;
12411 i++;
12412 }
12413 }
12414
12415 j = len;
12416 if (striptype != LEFTSTRIP) {
12417 j--;
12418 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012419 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012420 if (!_Py_ascii_whitespace[ch])
12421 break;
12422 j--;
12423 }
12424 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012425 }
12426 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012427 else {
12428 int kind = PyUnicode_KIND(self);
12429 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012430
Victor Stinnercc7af722013-04-09 22:39:24 +020012431 i = 0;
12432 if (striptype != RIGHTSTRIP) {
12433 while (i < len) {
12434 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12435 if (!Py_UNICODE_ISSPACE(ch))
12436 break;
12437 i++;
12438 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012439 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012440
12441 j = len;
12442 if (striptype != LEFTSTRIP) {
12443 j--;
12444 while (j >= i) {
12445 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12446 if (!Py_UNICODE_ISSPACE(ch))
12447 break;
12448 j--;
12449 }
12450 j++;
12451 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012452 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012453
Victor Stinner7931d9a2011-11-04 00:22:48 +010012454 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455}
12456
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012457
12458static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012459do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012460{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012461 if (sep != NULL && sep != Py_None) {
12462 if (PyUnicode_Check(sep))
12463 return _PyUnicode_XStrip(self, striptype, sep);
12464 else {
12465 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012466 "%s arg must be None or str",
12467 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012468 return NULL;
12469 }
12470 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012471
Benjamin Peterson14339b62009-01-31 16:36:08 +000012472 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012473}
12474
12475
INADA Naoki3ae20562017-01-16 20:41:20 +090012476/*[clinic input]
12477str.strip as unicode_strip
12478
12479 chars: object = None
12480 /
12481
Victor Stinner0c4a8282017-01-17 02:21:47 +010012482Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012483
12484If chars is given and not None, remove characters in chars instead.
12485[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012486
12487static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012488unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012489/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012490{
INADA Naoki3ae20562017-01-16 20:41:20 +090012491 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012492}
12493
12494
INADA Naoki3ae20562017-01-16 20:41:20 +090012495/*[clinic input]
12496str.lstrip as unicode_lstrip
12497
12498 chars: object = NULL
12499 /
12500
12501Return a copy of the string with leading whitespace removed.
12502
12503If chars is given and not None, remove characters in chars instead.
12504[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012505
12506static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012507unicode_lstrip_impl(PyObject *self, PyObject *chars)
12508/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012509{
INADA Naoki3ae20562017-01-16 20:41:20 +090012510 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012511}
12512
12513
INADA Naoki3ae20562017-01-16 20:41:20 +090012514/*[clinic input]
12515str.rstrip as unicode_rstrip
12516
12517 chars: object = NULL
12518 /
12519
12520Return a copy of the string with trailing whitespace removed.
12521
12522If chars is given and not None, remove characters in chars instead.
12523[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012524
12525static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012526unicode_rstrip_impl(PyObject *self, PyObject *chars)
12527/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012528{
INADA Naoki3ae20562017-01-16 20:41:20 +090012529 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012530}
12531
12532
Guido van Rossumd57fd912000-03-10 22:53:23 +000012533static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012534unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012535{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012536 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012537 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012538
Serhiy Storchaka05997252013-01-26 12:14:02 +020012539 if (len < 1)
12540 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012541
Victor Stinnerc4b49542011-12-11 22:44:26 +010012542 /* no repeat, return original string */
12543 if (len == 1)
12544 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012545
Benjamin Petersonbac79492012-01-14 13:34:47 -050012546 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012547 return NULL;
12548
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012549 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012550 PyErr_SetString(PyExc_OverflowError,
12551 "repeated string is too long");
12552 return NULL;
12553 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012554 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012555
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012556 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012557 if (!u)
12558 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012559 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 if (PyUnicode_GET_LENGTH(str) == 1) {
12562 const int kind = PyUnicode_KIND(str);
12563 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012564 if (kind == PyUnicode_1BYTE_KIND) {
12565 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012566 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012567 }
12568 else if (kind == PyUnicode_2BYTE_KIND) {
12569 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012570 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012571 ucs2[n] = fill_char;
12572 } else {
12573 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12574 assert(kind == PyUnicode_4BYTE_KIND);
12575 for (n = 0; n < len; ++n)
12576 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012577 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 }
12579 else {
12580 /* number of characters copied this far */
12581 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012582 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012583 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012584 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012586 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012588 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012589 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012590 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591 }
12592
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012593 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012594 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595}
12596
Alexander Belopolsky40018472011-02-26 01:02:56 +000012597PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012598PyUnicode_Replace(PyObject *str,
12599 PyObject *substr,
12600 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012601 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012603 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12604 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012605 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012606 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012607}
12608
INADA Naoki3ae20562017-01-16 20:41:20 +090012609/*[clinic input]
12610str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611
INADA Naoki3ae20562017-01-16 20:41:20 +090012612 old: unicode
12613 new: unicode
12614 count: Py_ssize_t = -1
12615 Maximum number of occurrences to replace.
12616 -1 (the default value) means replace all occurrences.
12617 /
12618
12619Return a copy with all occurrences of substring old replaced by new.
12620
12621If the optional argument count is given, only the first count occurrences are
12622replaced.
12623[clinic start generated code]*/
12624
12625static PyObject *
12626unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12627 Py_ssize_t count)
12628/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012630 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012631 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012632 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633}
12634
Alexander Belopolsky40018472011-02-26 01:02:56 +000012635static PyObject *
12636unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012638 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639 Py_ssize_t isize;
12640 Py_ssize_t osize, squote, dquote, i, o;
12641 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012642 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012643 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012645 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012646 return NULL;
12647
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012648 isize = PyUnicode_GET_LENGTH(unicode);
12649 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012650
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 /* Compute length of output, quote characters, and
12652 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012653 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012654 max = 127;
12655 squote = dquote = 0;
12656 ikind = PyUnicode_KIND(unicode);
12657 for (i = 0; i < isize; i++) {
12658 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012659 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012661 case '\'': squote++; break;
12662 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012663 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012664 incr = 2;
12665 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012666 default:
12667 /* Fast-path ASCII */
12668 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012669 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012670 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012671 ;
12672 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012673 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012675 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012677 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012678 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012679 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012681 if (osize > PY_SSIZE_T_MAX - incr) {
12682 PyErr_SetString(PyExc_OverflowError,
12683 "string is too long to generate repr");
12684 return NULL;
12685 }
12686 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012687 }
12688
12689 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012690 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012692 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012693 if (dquote)
12694 /* Both squote and dquote present. Use squote,
12695 and escape them */
12696 osize += squote;
12697 else
12698 quote = '"';
12699 }
Victor Stinner55c08782013-04-14 18:45:39 +020012700 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701
12702 repr = PyUnicode_New(osize, max);
12703 if (repr == NULL)
12704 return NULL;
12705 okind = PyUnicode_KIND(repr);
12706 odata = PyUnicode_DATA(repr);
12707
12708 PyUnicode_WRITE(okind, odata, 0, quote);
12709 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012710 if (unchanged) {
12711 _PyUnicode_FastCopyCharacters(repr, 1,
12712 unicode, 0,
12713 isize);
12714 }
12715 else {
12716 for (i = 0, o = 1; i < isize; i++) {
12717 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012718
Victor Stinner55c08782013-04-14 18:45:39 +020012719 /* Escape quotes and backslashes */
12720 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012721 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012722 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012723 continue;
12724 }
12725
12726 /* Map special whitespace to '\t', \n', '\r' */
12727 if (ch == '\t') {
12728 PyUnicode_WRITE(okind, odata, o++, '\\');
12729 PyUnicode_WRITE(okind, odata, o++, 't');
12730 }
12731 else if (ch == '\n') {
12732 PyUnicode_WRITE(okind, odata, o++, '\\');
12733 PyUnicode_WRITE(okind, odata, o++, 'n');
12734 }
12735 else if (ch == '\r') {
12736 PyUnicode_WRITE(okind, odata, o++, '\\');
12737 PyUnicode_WRITE(okind, odata, o++, 'r');
12738 }
12739
12740 /* Map non-printable US ASCII to '\xhh' */
12741 else if (ch < ' ' || ch == 0x7F) {
12742 PyUnicode_WRITE(okind, odata, o++, '\\');
12743 PyUnicode_WRITE(okind, odata, o++, 'x');
12744 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12745 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12746 }
12747
12748 /* Copy ASCII characters as-is */
12749 else if (ch < 0x7F) {
12750 PyUnicode_WRITE(okind, odata, o++, ch);
12751 }
12752
12753 /* Non-ASCII characters */
12754 else {
12755 /* Map Unicode whitespace and control characters
12756 (categories Z* and C* except ASCII space)
12757 */
12758 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12759 PyUnicode_WRITE(okind, odata, o++, '\\');
12760 /* Map 8-bit characters to '\xhh' */
12761 if (ch <= 0xff) {
12762 PyUnicode_WRITE(okind, odata, o++, 'x');
12763 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12764 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12765 }
12766 /* Map 16-bit characters to '\uxxxx' */
12767 else if (ch <= 0xffff) {
12768 PyUnicode_WRITE(okind, odata, o++, 'u');
12769 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12770 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12771 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12772 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12773 }
12774 /* Map 21-bit characters to '\U00xxxxxx' */
12775 else {
12776 PyUnicode_WRITE(okind, odata, o++, 'U');
12777 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12778 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12779 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12780 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12781 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12782 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12783 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12784 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12785 }
12786 }
12787 /* Copy characters as-is */
12788 else {
12789 PyUnicode_WRITE(okind, odata, o++, ch);
12790 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012791 }
12792 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012793 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012794 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012795 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012796 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797}
12798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012799PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012800 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801\n\
12802Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012803such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012804arguments start and end are interpreted as in slice notation.\n\
12805\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012806Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807
12808static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012809unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012811 /* initialize variables to prevent gcc warning */
12812 PyObject *substring = NULL;
12813 Py_ssize_t start = 0;
12814 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012815 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012817 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012818 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012819
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012820 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012821 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012822
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012823 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012824
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012825 if (result == -2)
12826 return NULL;
12827
Christian Heimes217cfd12007-12-02 14:31:20 +000012828 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829}
12830
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012831PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012832 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012833\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012834Return the highest index in S where substring sub is found,\n\
12835such that sub is contained within S[start:end]. Optional\n\
12836arguments start and end are interpreted as in slice notation.\n\
12837\n\
12838Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012839
12840static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012841unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012842{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012843 /* initialize variables to prevent gcc warning */
12844 PyObject *substring = NULL;
12845 Py_ssize_t start = 0;
12846 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012847 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012848
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012849 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012850 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012851
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012852 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012853 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012855 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012857 if (result == -2)
12858 return NULL;
12859
Guido van Rossumd57fd912000-03-10 22:53:23 +000012860 if (result < 0) {
12861 PyErr_SetString(PyExc_ValueError, "substring not found");
12862 return NULL;
12863 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012864
Christian Heimes217cfd12007-12-02 14:31:20 +000012865 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012866}
12867
INADA Naoki3ae20562017-01-16 20:41:20 +090012868/*[clinic input]
12869str.rjust as unicode_rjust
12870
12871 width: Py_ssize_t
12872 fillchar: Py_UCS4 = ' '
12873 /
12874
12875Return a right-justified string of length width.
12876
12877Padding is done using the specified fill character (default is a space).
12878[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012879
12880static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012881unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12882/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012883{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012884 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012885 return NULL;
12886
Victor Stinnerc4b49542011-12-11 22:44:26 +010012887 if (PyUnicode_GET_LENGTH(self) >= width)
12888 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012889
Victor Stinnerc4b49542011-12-11 22:44:26 +010012890 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891}
12892
Alexander Belopolsky40018472011-02-26 01:02:56 +000012893PyObject *
12894PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012895{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012896 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012897 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012898
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012899 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900}
12901
INADA Naoki3ae20562017-01-16 20:41:20 +090012902/*[clinic input]
12903str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012904
INADA Naoki3ae20562017-01-16 20:41:20 +090012905 sep: object = None
12906 The delimiter according which to split the string.
12907 None (the default value) means split according to any whitespace,
12908 and discard empty strings from the result.
12909 maxsplit: Py_ssize_t = -1
12910 Maximum number of splits to do.
12911 -1 (the default value) means no limit.
12912
12913Return a list of the words in the string, using sep as the delimiter string.
12914[clinic start generated code]*/
12915
12916static PyObject *
12917unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12918/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012919{
INADA Naoki3ae20562017-01-16 20:41:20 +090012920 if (sep == Py_None)
12921 return split(self, NULL, maxsplit);
12922 if (PyUnicode_Check(sep))
12923 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012924
Victor Stinner998b8062018-09-12 00:23:25 +020012925 PyErr_Format(PyExc_TypeError,
12926 "must be str or None, not %.100s",
12927 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012928 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012929}
12930
Thomas Wouters477c8d52006-05-27 19:21:47 +000012931PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012932PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012933{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012934 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012935 int kind1, kind2;
12936 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012937 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012938
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012939 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012940 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012941
Victor Stinner14f8f022011-10-05 20:58:25 +020012942 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012943 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012944 len1 = PyUnicode_GET_LENGTH(str_obj);
12945 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012946 if (kind1 < kind2 || len1 < len2) {
12947 _Py_INCREF_UNICODE_EMPTY();
12948 if (!unicode_empty)
12949 out = NULL;
12950 else {
12951 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12952 Py_DECREF(unicode_empty);
12953 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012954 return out;
12955 }
12956 buf1 = PyUnicode_DATA(str_obj);
12957 buf2 = PyUnicode_DATA(sep_obj);
12958 if (kind2 != kind1) {
12959 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12960 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012961 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012963
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012964 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012965 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012966 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12967 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12968 else
12969 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012970 break;
12971 case PyUnicode_2BYTE_KIND:
12972 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12973 break;
12974 case PyUnicode_4BYTE_KIND:
12975 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12976 break;
12977 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012978 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012979 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012980
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012981 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012982 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012983
12984 return out;
12985}
12986
12987
12988PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012989PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012990{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012991 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012992 int kind1, kind2;
12993 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012995
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012996 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012997 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012998
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012999 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013001 len1 = PyUnicode_GET_LENGTH(str_obj);
13002 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013003 if (kind1 < kind2 || len1 < len2) {
13004 _Py_INCREF_UNICODE_EMPTY();
13005 if (!unicode_empty)
13006 out = NULL;
13007 else {
13008 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
13009 Py_DECREF(unicode_empty);
13010 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013011 return out;
13012 }
13013 buf1 = PyUnicode_DATA(str_obj);
13014 buf2 = PyUnicode_DATA(sep_obj);
13015 if (kind2 != kind1) {
13016 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13017 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013018 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013019 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013020
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013021 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013022 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013023 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13024 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13025 else
13026 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013027 break;
13028 case PyUnicode_2BYTE_KIND:
13029 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13030 break;
13031 case PyUnicode_4BYTE_KIND:
13032 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13033 break;
13034 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013035 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013036 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013037
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013038 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013039 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013040
13041 return out;
13042}
13043
INADA Naoki3ae20562017-01-16 20:41:20 +090013044/*[clinic input]
13045str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013046
INADA Naoki3ae20562017-01-16 20:41:20 +090013047 sep: object
13048 /
13049
13050Partition the string into three parts using the given separator.
13051
13052This will search for the separator in the string. If the separator is found,
13053returns a 3-tuple containing the part before the separator, the separator
13054itself, and the part after it.
13055
13056If the separator is not found, returns a 3-tuple containing the original string
13057and two empty strings.
13058[clinic start generated code]*/
13059
13060static PyObject *
13061unicode_partition(PyObject *self, PyObject *sep)
13062/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013063{
INADA Naoki3ae20562017-01-16 20:41:20 +090013064 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013065}
13066
INADA Naoki3ae20562017-01-16 20:41:20 +090013067/*[clinic input]
13068str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013069
INADA Naoki3ae20562017-01-16 20:41:20 +090013070Partition the string into three parts using the given separator.
13071
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013072This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090013073the separator is found, returns a 3-tuple containing the part before the
13074separator, the separator itself, and the part after it.
13075
13076If the separator is not found, returns a 3-tuple containing two empty strings
13077and the original string.
13078[clinic start generated code]*/
13079
13080static PyObject *
13081unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013082/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013083{
INADA Naoki3ae20562017-01-16 20:41:20 +090013084 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013085}
13086
Alexander Belopolsky40018472011-02-26 01:02:56 +000013087PyObject *
13088PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013089{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013090 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013091 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013092
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013093 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013094}
13095
INADA Naoki3ae20562017-01-16 20:41:20 +090013096/*[clinic input]
13097str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013098
INADA Naoki3ae20562017-01-16 20:41:20 +090013099Return a list of the words in the string, using sep as the delimiter string.
13100
13101Splits are done starting at the end of the string and working to the front.
13102[clinic start generated code]*/
13103
13104static PyObject *
13105unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13106/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013107{
INADA Naoki3ae20562017-01-16 20:41:20 +090013108 if (sep == Py_None)
13109 return rsplit(self, NULL, maxsplit);
13110 if (PyUnicode_Check(sep))
13111 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013112
Victor Stinner998b8062018-09-12 00:23:25 +020013113 PyErr_Format(PyExc_TypeError,
13114 "must be str or None, not %.100s",
13115 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013116 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013117}
13118
INADA Naoki3ae20562017-01-16 20:41:20 +090013119/*[clinic input]
13120str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013121
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013122 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013123
13124Return a list of the lines in the string, breaking at line boundaries.
13125
13126Line breaks are not included in the resulting list unless keepends is given and
13127true.
13128[clinic start generated code]*/
13129
13130static PyObject *
13131unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013132/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013134 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013135}
13136
13137static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013138PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013139{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013140 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013141}
13142
INADA Naoki3ae20562017-01-16 20:41:20 +090013143/*[clinic input]
13144str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013145
INADA Naoki3ae20562017-01-16 20:41:20 +090013146Convert uppercase characters to lowercase and lowercase characters to uppercase.
13147[clinic start generated code]*/
13148
13149static PyObject *
13150unicode_swapcase_impl(PyObject *self)
13151/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013152{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013153 if (PyUnicode_READY(self) == -1)
13154 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013155 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156}
13157
Larry Hastings61272b72014-01-07 12:41:53 -080013158/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013159
Larry Hastings31826802013-10-19 00:09:25 -070013160@staticmethod
13161str.maketrans as unicode_maketrans
13162
13163 x: object
13164
13165 y: unicode=NULL
13166
13167 z: unicode=NULL
13168
13169 /
13170
13171Return a translation table usable for str.translate().
13172
13173If there is only one argument, it must be a dictionary mapping Unicode
13174ordinals (integers) or characters to Unicode ordinals, strings or None.
13175Character keys will be then converted to ordinals.
13176If there are two arguments, they must be strings of equal length, and
13177in the resulting dictionary, each character in x will be mapped to the
13178character at the same position in y. If there is a third argument, it
13179must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013180[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013181
Larry Hastings31826802013-10-19 00:09:25 -070013182static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013183unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013184/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013185{
Georg Brandlceee0772007-11-27 23:48:05 +000013186 PyObject *new = NULL, *key, *value;
13187 Py_ssize_t i = 0;
13188 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013189
Georg Brandlceee0772007-11-27 23:48:05 +000013190 new = PyDict_New();
13191 if (!new)
13192 return NULL;
13193 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013194 int x_kind, y_kind, z_kind;
13195 void *x_data, *y_data, *z_data;
13196
Georg Brandlceee0772007-11-27 23:48:05 +000013197 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013198 if (!PyUnicode_Check(x)) {
13199 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13200 "be a string if there is a second argument");
13201 goto err;
13202 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013203 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013204 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13205 "arguments must have equal length");
13206 goto err;
13207 }
13208 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013209 x_kind = PyUnicode_KIND(x);
13210 y_kind = PyUnicode_KIND(y);
13211 x_data = PyUnicode_DATA(x);
13212 y_data = PyUnicode_DATA(y);
13213 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13214 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013215 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013216 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013217 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013218 if (!value) {
13219 Py_DECREF(key);
13220 goto err;
13221 }
Georg Brandlceee0772007-11-27 23:48:05 +000013222 res = PyDict_SetItem(new, key, value);
13223 Py_DECREF(key);
13224 Py_DECREF(value);
13225 if (res < 0)
13226 goto err;
13227 }
13228 /* create entries for deleting chars in z */
13229 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013230 z_kind = PyUnicode_KIND(z);
13231 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013232 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013233 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013234 if (!key)
13235 goto err;
13236 res = PyDict_SetItem(new, key, Py_None);
13237 Py_DECREF(key);
13238 if (res < 0)
13239 goto err;
13240 }
13241 }
13242 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013243 int kind;
13244 void *data;
13245
Georg Brandlceee0772007-11-27 23:48:05 +000013246 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013247 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013248 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13249 "to maketrans it must be a dict");
13250 goto err;
13251 }
13252 /* copy entries into the new dict, converting string keys to int keys */
13253 while (PyDict_Next(x, &i, &key, &value)) {
13254 if (PyUnicode_Check(key)) {
13255 /* convert string keys to integer keys */
13256 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013257 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013258 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13259 "table must be of length 1");
13260 goto err;
13261 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013262 kind = PyUnicode_KIND(key);
13263 data = PyUnicode_DATA(key);
13264 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013265 if (!newkey)
13266 goto err;
13267 res = PyDict_SetItem(new, newkey, value);
13268 Py_DECREF(newkey);
13269 if (res < 0)
13270 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013271 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013272 /* just keep integer keys */
13273 if (PyDict_SetItem(new, key, value) < 0)
13274 goto err;
13275 } else {
13276 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13277 "be strings or integers");
13278 goto err;
13279 }
13280 }
13281 }
13282 return new;
13283 err:
13284 Py_DECREF(new);
13285 return NULL;
13286}
13287
INADA Naoki3ae20562017-01-16 20:41:20 +090013288/*[clinic input]
13289str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013290
INADA Naoki3ae20562017-01-16 20:41:20 +090013291 table: object
13292 Translation table, which must be a mapping of Unicode ordinals to
13293 Unicode ordinals, strings, or None.
13294 /
13295
13296Replace each character in the string using the given translation table.
13297
13298The table must implement lookup/indexing via __getitem__, for instance a
13299dictionary or list. If this operation raises LookupError, the character is
13300left untouched. Characters mapped to None are deleted.
13301[clinic start generated code]*/
13302
13303static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013304unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013305/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013306{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013307 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013308}
13309
INADA Naoki3ae20562017-01-16 20:41:20 +090013310/*[clinic input]
13311str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013312
INADA Naoki3ae20562017-01-16 20:41:20 +090013313Return a copy of the string converted to uppercase.
13314[clinic start generated code]*/
13315
13316static PyObject *
13317unicode_upper_impl(PyObject *self)
13318/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013319{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013320 if (PyUnicode_READY(self) == -1)
13321 return NULL;
13322 if (PyUnicode_IS_ASCII(self))
13323 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013324 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013325}
13326
INADA Naoki3ae20562017-01-16 20:41:20 +090013327/*[clinic input]
13328str.zfill as unicode_zfill
13329
13330 width: Py_ssize_t
13331 /
13332
13333Pad a numeric string with zeros on the left, to fill a field of the given width.
13334
13335The string is never truncated.
13336[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337
13338static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013339unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013340/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013341{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013342 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013343 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013344 int kind;
13345 void *data;
13346 Py_UCS4 chr;
13347
Benjamin Petersonbac79492012-01-14 13:34:47 -050013348 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013349 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013350
Victor Stinnerc4b49542011-12-11 22:44:26 +010013351 if (PyUnicode_GET_LENGTH(self) >= width)
13352 return unicode_result_unchanged(self);
13353
13354 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013355
13356 u = pad(self, fill, 0, '0');
13357
Walter Dörwald068325e2002-04-15 13:36:47 +000013358 if (u == NULL)
13359 return NULL;
13360
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013361 kind = PyUnicode_KIND(u);
13362 data = PyUnicode_DATA(u);
13363 chr = PyUnicode_READ(kind, data, fill);
13364
13365 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013366 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013367 PyUnicode_WRITE(kind, data, 0, chr);
13368 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013369 }
13370
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013371 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013372 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013373}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013374
13375#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013376static PyObject *
13377unicode__decimal2ascii(PyObject *self)
13378{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013379 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013380}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013381#endif
13382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013383PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013384 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013385\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013386Return True if S starts with the specified prefix, False otherwise.\n\
13387With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013388With optional end, stop comparing S at that position.\n\
13389prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013390
13391static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013392unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013393 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013394{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013395 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013396 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013397 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013398 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013399 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013400
Jesus Ceaac451502011-04-20 17:09:23 +020013401 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013402 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013403 if (PyTuple_Check(subobj)) {
13404 Py_ssize_t i;
13405 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013406 substring = PyTuple_GET_ITEM(subobj, i);
13407 if (!PyUnicode_Check(substring)) {
13408 PyErr_Format(PyExc_TypeError,
13409 "tuple for startswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013410 "not %.100s",
13411 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013412 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013413 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013414 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013415 if (result == -1)
13416 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013417 if (result) {
13418 Py_RETURN_TRUE;
13419 }
13420 }
13421 /* nothing matched */
13422 Py_RETURN_FALSE;
13423 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013424 if (!PyUnicode_Check(subobj)) {
13425 PyErr_Format(PyExc_TypeError,
13426 "startswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013427 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013428 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013429 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013430 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013431 if (result == -1)
13432 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013433 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013434}
13435
13436
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013437PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013438 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013439\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013440Return True if S ends with the specified suffix, False otherwise.\n\
13441With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013442With optional end, stop comparing S at that position.\n\
13443suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013444
13445static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013446unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013447 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013448{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013449 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013450 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013451 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013452 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013453 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013454
Jesus Ceaac451502011-04-20 17:09:23 +020013455 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013457 if (PyTuple_Check(subobj)) {
13458 Py_ssize_t i;
13459 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013460 substring = PyTuple_GET_ITEM(subobj, i);
13461 if (!PyUnicode_Check(substring)) {
13462 PyErr_Format(PyExc_TypeError,
13463 "tuple for endswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013464 "not %.100s",
13465 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013466 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013467 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013468 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013469 if (result == -1)
13470 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013471 if (result) {
13472 Py_RETURN_TRUE;
13473 }
13474 }
13475 Py_RETURN_FALSE;
13476 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013477 if (!PyUnicode_Check(subobj)) {
13478 PyErr_Format(PyExc_TypeError,
13479 "endswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013480 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013481 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013482 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013483 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013484 if (result == -1)
13485 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013486 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013487}
13488
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013489static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013490_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013491{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013492 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13493 writer->data = PyUnicode_DATA(writer->buffer);
13494
13495 if (!writer->readonly) {
13496 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013497 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013498 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013499 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013500 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13501 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13502 writer->kind = PyUnicode_WCHAR_KIND;
13503 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13504
Victor Stinner8f674cc2013-04-17 23:02:17 +020013505 /* Copy-on-write mode: set buffer size to 0 so
13506 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13507 * next write. */
13508 writer->size = 0;
13509 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013510}
13511
Victor Stinnerd3f08822012-05-29 12:57:52 +020013512void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013513_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013514{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013515 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013516
13517 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013518 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013519
13520 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13521 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13522 writer->kind = PyUnicode_WCHAR_KIND;
13523 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013524}
13525
Victor Stinnerd3f08822012-05-29 12:57:52 +020013526int
13527_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13528 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013529{
13530 Py_ssize_t newlen;
13531 PyObject *newbuffer;
13532
Victor Stinner2740e462016-09-06 16:58:36 -070013533 assert(maxchar <= MAX_UNICODE);
13534
Victor Stinnerca9381e2015-09-22 00:58:32 +020013535 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013536 assert((maxchar > writer->maxchar && length >= 0)
13537 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013538
Victor Stinner202fdca2012-05-07 12:47:02 +020013539 if (length > PY_SSIZE_T_MAX - writer->pos) {
13540 PyErr_NoMemory();
13541 return -1;
13542 }
13543 newlen = writer->pos + length;
13544
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013545 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013546
Victor Stinnerd3f08822012-05-29 12:57:52 +020013547 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013548 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013549 if (writer->overallocate
13550 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13551 /* overallocate to limit the number of realloc() */
13552 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013553 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013554 if (newlen < writer->min_length)
13555 newlen = writer->min_length;
13556
Victor Stinnerd3f08822012-05-29 12:57:52 +020013557 writer->buffer = PyUnicode_New(newlen, maxchar);
13558 if (writer->buffer == NULL)
13559 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013560 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013561 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013562 if (writer->overallocate
13563 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13564 /* overallocate to limit the number of realloc() */
13565 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013566 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013567 if (newlen < writer->min_length)
13568 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013569
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013570 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013571 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013572 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013573 newbuffer = PyUnicode_New(newlen, maxchar);
13574 if (newbuffer == NULL)
13575 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013576 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13577 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013578 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013579 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013580 }
13581 else {
13582 newbuffer = resize_compact(writer->buffer, newlen);
13583 if (newbuffer == NULL)
13584 return -1;
13585 }
13586 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013587 }
13588 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013589 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013590 newbuffer = PyUnicode_New(writer->size, maxchar);
13591 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013592 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013593 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13594 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013595 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013596 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013597 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013598 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013599
13600#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013601}
13602
Victor Stinnerca9381e2015-09-22 00:58:32 +020013603int
13604_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13605 enum PyUnicode_Kind kind)
13606{
13607 Py_UCS4 maxchar;
13608
13609 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13610 assert(writer->kind < kind);
13611
13612 switch (kind)
13613 {
13614 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13615 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13616 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13617 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013618 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013619 }
13620
13621 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13622}
13623
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013624static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013625_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013626{
Victor Stinner2740e462016-09-06 16:58:36 -070013627 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013628 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13629 return -1;
13630 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13631 writer->pos++;
13632 return 0;
13633}
13634
13635int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013636_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13637{
13638 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13639}
13640
13641int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013642_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13643{
13644 Py_UCS4 maxchar;
13645 Py_ssize_t len;
13646
13647 if (PyUnicode_READY(str) == -1)
13648 return -1;
13649 len = PyUnicode_GET_LENGTH(str);
13650 if (len == 0)
13651 return 0;
13652 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13653 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013654 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013655 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013656 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013657 Py_INCREF(str);
13658 writer->buffer = str;
13659 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013660 writer->pos += len;
13661 return 0;
13662 }
13663 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13664 return -1;
13665 }
13666 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13667 str, 0, len);
13668 writer->pos += len;
13669 return 0;
13670}
13671
Victor Stinnere215d962012-10-06 23:03:36 +020013672int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013673_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13674 Py_ssize_t start, Py_ssize_t end)
13675{
13676 Py_UCS4 maxchar;
13677 Py_ssize_t len;
13678
13679 if (PyUnicode_READY(str) == -1)
13680 return -1;
13681
13682 assert(0 <= start);
13683 assert(end <= PyUnicode_GET_LENGTH(str));
13684 assert(start <= end);
13685
13686 if (end == 0)
13687 return 0;
13688
13689 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13690 return _PyUnicodeWriter_WriteStr(writer, str);
13691
13692 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13693 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13694 else
13695 maxchar = writer->maxchar;
13696 len = end - start;
13697
13698 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13699 return -1;
13700
13701 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13702 str, start, len);
13703 writer->pos += len;
13704 return 0;
13705}
13706
13707int
Victor Stinner4a587072013-11-19 12:54:53 +010013708_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13709 const char *ascii, Py_ssize_t len)
13710{
13711 if (len == -1)
13712 len = strlen(ascii);
13713
13714 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13715
13716 if (writer->buffer == NULL && !writer->overallocate) {
13717 PyObject *str;
13718
13719 str = _PyUnicode_FromASCII(ascii, len);
13720 if (str == NULL)
13721 return -1;
13722
13723 writer->readonly = 1;
13724 writer->buffer = str;
13725 _PyUnicodeWriter_Update(writer);
13726 writer->pos += len;
13727 return 0;
13728 }
13729
13730 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13731 return -1;
13732
13733 switch (writer->kind)
13734 {
13735 case PyUnicode_1BYTE_KIND:
13736 {
13737 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13738 Py_UCS1 *data = writer->data;
13739
Christian Heimesf051e432016-09-13 20:22:02 +020013740 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013741 break;
13742 }
13743 case PyUnicode_2BYTE_KIND:
13744 {
13745 _PyUnicode_CONVERT_BYTES(
13746 Py_UCS1, Py_UCS2,
13747 ascii, ascii + len,
13748 (Py_UCS2 *)writer->data + writer->pos);
13749 break;
13750 }
13751 case PyUnicode_4BYTE_KIND:
13752 {
13753 _PyUnicode_CONVERT_BYTES(
13754 Py_UCS1, Py_UCS4,
13755 ascii, ascii + len,
13756 (Py_UCS4 *)writer->data + writer->pos);
13757 break;
13758 }
13759 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013760 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013761 }
13762
13763 writer->pos += len;
13764 return 0;
13765}
13766
13767int
13768_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13769 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013770{
13771 Py_UCS4 maxchar;
13772
13773 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13774 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13775 return -1;
13776 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13777 writer->pos += len;
13778 return 0;
13779}
13780
Victor Stinnerd3f08822012-05-29 12:57:52 +020013781PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013782_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013783{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013784 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013785
Victor Stinnerd3f08822012-05-29 12:57:52 +020013786 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013787 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013788 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013789 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013790
13791 str = writer->buffer;
13792 writer->buffer = NULL;
13793
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013794 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013795 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13796 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013797 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013798
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013799 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13800 PyObject *str2;
13801 str2 = resize_compact(str, writer->pos);
13802 if (str2 == NULL) {
13803 Py_DECREF(str);
13804 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013805 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013806 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013807 }
13808
Victor Stinner15a0bd32013-07-08 22:29:55 +020013809 assert(_PyUnicode_CheckConsistency(str, 1));
13810 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013811}
13812
Victor Stinnerd3f08822012-05-29 12:57:52 +020013813void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013814_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013815{
13816 Py_CLEAR(writer->buffer);
13817}
13818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013819#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013820
13821PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013822 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013823\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013824Return a formatted version of S, using substitutions from args and kwargs.\n\
13825The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013826
Eric Smith27bbca62010-11-04 17:06:58 +000013827PyDoc_STRVAR(format_map__doc__,
13828 "S.format_map(mapping) -> str\n\
13829\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013830Return a formatted version of S, using substitutions from mapping.\n\
13831The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013832
INADA Naoki3ae20562017-01-16 20:41:20 +090013833/*[clinic input]
13834str.__format__ as unicode___format__
13835
13836 format_spec: unicode
13837 /
13838
13839Return a formatted version of the string as described by format_spec.
13840[clinic start generated code]*/
13841
Eric Smith4a7d76d2008-05-30 18:10:19 +000013842static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013843unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013844/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013845{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013846 _PyUnicodeWriter writer;
13847 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013848
Victor Stinnerd3f08822012-05-29 12:57:52 +020013849 if (PyUnicode_READY(self) == -1)
13850 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013851 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013852 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13853 self, format_spec, 0,
13854 PyUnicode_GET_LENGTH(format_spec));
13855 if (ret == -1) {
13856 _PyUnicodeWriter_Dealloc(&writer);
13857 return NULL;
13858 }
13859 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013860}
13861
INADA Naoki3ae20562017-01-16 20:41:20 +090013862/*[clinic input]
13863str.__sizeof__ as unicode_sizeof
13864
13865Return the size of the string in memory, in bytes.
13866[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013867
13868static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013869unicode_sizeof_impl(PyObject *self)
13870/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013871{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013872 Py_ssize_t size;
13873
13874 /* If it's a compact object, account for base structure +
13875 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013876 if (PyUnicode_IS_COMPACT_ASCII(self))
13877 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13878 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013879 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013880 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013881 else {
13882 /* If it is a two-block object, account for base object, and
13883 for character block if present. */
13884 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013885 if (_PyUnicode_DATA_ANY(self))
13886 size += (PyUnicode_GET_LENGTH(self) + 1) *
13887 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013888 }
13889 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013890 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013891 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13892 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13893 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13894 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013895
13896 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013897}
13898
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013899static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013900unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013901{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013902 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 if (!copy)
13904 return NULL;
13905 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013906}
13907
Guido van Rossumd57fd912000-03-10 22:53:23 +000013908static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013909 UNICODE_ENCODE_METHODDEF
13910 UNICODE_REPLACE_METHODDEF
13911 UNICODE_SPLIT_METHODDEF
13912 UNICODE_RSPLIT_METHODDEF
13913 UNICODE_JOIN_METHODDEF
13914 UNICODE_CAPITALIZE_METHODDEF
13915 UNICODE_CASEFOLD_METHODDEF
13916 UNICODE_TITLE_METHODDEF
13917 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013918 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013919 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013920 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013921 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013922 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013923 UNICODE_LJUST_METHODDEF
13924 UNICODE_LOWER_METHODDEF
13925 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013926 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13927 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013928 UNICODE_RJUST_METHODDEF
13929 UNICODE_RSTRIP_METHODDEF
13930 UNICODE_RPARTITION_METHODDEF
13931 UNICODE_SPLITLINES_METHODDEF
13932 UNICODE_STRIP_METHODDEF
13933 UNICODE_SWAPCASE_METHODDEF
13934 UNICODE_TRANSLATE_METHODDEF
13935 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013936 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13937 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013938 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013939 UNICODE_ISLOWER_METHODDEF
13940 UNICODE_ISUPPER_METHODDEF
13941 UNICODE_ISTITLE_METHODDEF
13942 UNICODE_ISSPACE_METHODDEF
13943 UNICODE_ISDECIMAL_METHODDEF
13944 UNICODE_ISDIGIT_METHODDEF
13945 UNICODE_ISNUMERIC_METHODDEF
13946 UNICODE_ISALPHA_METHODDEF
13947 UNICODE_ISALNUM_METHODDEF
13948 UNICODE_ISIDENTIFIER_METHODDEF
13949 UNICODE_ISPRINTABLE_METHODDEF
13950 UNICODE_ZFILL_METHODDEF
Eric Smith9cd1e092007-08-31 18:39:38 +000013951 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013952 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013953 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013954 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013955 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013956#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013957 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013958 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013959#endif
13960
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013961 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013962 {NULL, NULL}
13963};
13964
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013965static PyObject *
13966unicode_mod(PyObject *v, PyObject *w)
13967{
Brian Curtindfc80e32011-08-10 20:28:54 -050013968 if (!PyUnicode_Check(v))
13969 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013970 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013971}
13972
13973static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013974 0, /*nb_add*/
13975 0, /*nb_subtract*/
13976 0, /*nb_multiply*/
13977 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013978};
13979
Guido van Rossumd57fd912000-03-10 22:53:23 +000013980static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013981 (lenfunc) unicode_length, /* sq_length */
13982 PyUnicode_Concat, /* sq_concat */
13983 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13984 (ssizeargfunc) unicode_getitem, /* sq_item */
13985 0, /* sq_slice */
13986 0, /* sq_ass_item */
13987 0, /* sq_ass_slice */
13988 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013989};
13990
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013991static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013992unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013993{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013994 if (PyUnicode_READY(self) == -1)
13995 return NULL;
13996
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013997 if (PyIndex_Check(item)) {
13998 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013999 if (i == -1 && PyErr_Occurred())
14000 return NULL;
14001 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014002 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014003 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014004 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000014005 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014006 PyObject *result;
14007 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014008 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014009 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014010
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014011 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014012 return NULL;
14013 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014014 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14015 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014016
14017 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020014018 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014019 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010014020 slicelength == PyUnicode_GET_LENGTH(self)) {
14021 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000014022 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014023 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020014024 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014025 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014026 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014027 src_kind = PyUnicode_KIND(self);
14028 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020014029 if (!PyUnicode_IS_ASCII(self)) {
14030 kind_limit = kind_maxchar_limit(src_kind);
14031 max_char = 0;
14032 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14033 ch = PyUnicode_READ(src_kind, src_data, cur);
14034 if (ch > max_char) {
14035 max_char = ch;
14036 if (max_char >= kind_limit)
14037 break;
14038 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014039 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014040 }
Victor Stinner55c99112011-10-13 01:17:06 +020014041 else
14042 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014043 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014044 if (result == NULL)
14045 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014046 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014047 dest_data = PyUnicode_DATA(result);
14048
14049 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014050 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14051 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014052 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014053 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014054 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014055 } else {
14056 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14057 return NULL;
14058 }
14059}
14060
14061static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014062 (lenfunc)unicode_length, /* mp_length */
14063 (binaryfunc)unicode_subscript, /* mp_subscript */
14064 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014065};
14066
Guido van Rossumd57fd912000-03-10 22:53:23 +000014067
Guido van Rossumd57fd912000-03-10 22:53:23 +000014068/* Helpers for PyUnicode_Format() */
14069
Victor Stinnera47082312012-10-04 02:19:54 +020014070struct unicode_formatter_t {
14071 PyObject *args;
14072 int args_owned;
14073 Py_ssize_t arglen, argidx;
14074 PyObject *dict;
14075
14076 enum PyUnicode_Kind fmtkind;
14077 Py_ssize_t fmtcnt, fmtpos;
14078 void *fmtdata;
14079 PyObject *fmtstr;
14080
14081 _PyUnicodeWriter writer;
14082};
14083
14084struct unicode_format_arg_t {
14085 Py_UCS4 ch;
14086 int flags;
14087 Py_ssize_t width;
14088 int prec;
14089 int sign;
14090};
14091
Guido van Rossumd57fd912000-03-10 22:53:23 +000014092static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014093unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014094{
Victor Stinnera47082312012-10-04 02:19:54 +020014095 Py_ssize_t argidx = ctx->argidx;
14096
14097 if (argidx < ctx->arglen) {
14098 ctx->argidx++;
14099 if (ctx->arglen < 0)
14100 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014101 else
Victor Stinnera47082312012-10-04 02:19:54 +020014102 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014103 }
14104 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014105 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014106 return NULL;
14107}
14108
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014109/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014110
Victor Stinnera47082312012-10-04 02:19:54 +020014111/* Format a float into the writer if the writer is not NULL, or into *p_output
14112 otherwise.
14113
14114 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014115static int
Victor Stinnera47082312012-10-04 02:19:54 +020014116formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14117 PyObject **p_output,
14118 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014119{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014120 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014121 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014122 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014123 int prec;
14124 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014125
Guido van Rossumd57fd912000-03-10 22:53:23 +000014126 x = PyFloat_AsDouble(v);
14127 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014128 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014129
Victor Stinnera47082312012-10-04 02:19:54 +020014130 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014131 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014132 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014133
Victor Stinnera47082312012-10-04 02:19:54 +020014134 if (arg->flags & F_ALT)
14135 dtoa_flags = Py_DTSF_ALT;
14136 else
14137 dtoa_flags = 0;
14138 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014139 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014140 return -1;
14141 len = strlen(p);
14142 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014143 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014144 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014145 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014146 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014147 }
14148 else
14149 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014150 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014151 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014152}
14153
Victor Stinnerd0880d52012-04-27 23:40:13 +020014154/* formatlong() emulates the format codes d, u, o, x and X, and
14155 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14156 * Python's regular ints.
14157 * Return value: a new PyUnicodeObject*, or NULL if error.
14158 * The output string is of the form
14159 * "-"? ("0x" | "0X")? digit+
14160 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14161 * set in flags. The case of hex digits will be correct,
14162 * There will be at least prec digits, zero-filled on the left if
14163 * necessary to get that many.
14164 * val object to be converted
14165 * flags bitmask of format flags; only F_ALT is looked at
14166 * prec minimum number of digits; 0-fill on left if needed
14167 * type a character in [duoxX]; u acts the same as d
14168 *
14169 * CAUTION: o, x and X conversions on regular ints can never
14170 * produce a '-' sign, but can for Python's unbounded ints.
14171 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014172PyObject *
14173_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014174{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014175 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014176 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014177 Py_ssize_t i;
14178 int sign; /* 1 if '-', else 0 */
14179 int len; /* number of characters */
14180 Py_ssize_t llen;
14181 int numdigits; /* len == numnondigits + numdigits */
14182 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014183
Victor Stinnerd0880d52012-04-27 23:40:13 +020014184 /* Avoid exceeding SSIZE_T_MAX */
14185 if (prec > INT_MAX-3) {
14186 PyErr_SetString(PyExc_OverflowError,
14187 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014188 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014189 }
14190
14191 assert(PyLong_Check(val));
14192
14193 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014194 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014195 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014196 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014197 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014198 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014199 /* int and int subclasses should print numerically when a numeric */
14200 /* format code is used (see issue18780) */
14201 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014202 break;
14203 case 'o':
14204 numnondigits = 2;
14205 result = PyNumber_ToBase(val, 8);
14206 break;
14207 case 'x':
14208 case 'X':
14209 numnondigits = 2;
14210 result = PyNumber_ToBase(val, 16);
14211 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014212 }
14213 if (!result)
14214 return NULL;
14215
14216 assert(unicode_modifiable(result));
14217 assert(PyUnicode_IS_READY(result));
14218 assert(PyUnicode_IS_ASCII(result));
14219
14220 /* To modify the string in-place, there can only be one reference. */
14221 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014222 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014223 PyErr_BadInternalCall();
14224 return NULL;
14225 }
14226 buf = PyUnicode_DATA(result);
14227 llen = PyUnicode_GET_LENGTH(result);
14228 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014229 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014230 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014231 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014232 return NULL;
14233 }
14234 len = (int)llen;
14235 sign = buf[0] == '-';
14236 numnondigits += sign;
14237 numdigits = len - numnondigits;
14238 assert(numdigits > 0);
14239
14240 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014241 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014242 (type == 'o' || type == 'x' || type == 'X'))) {
14243 assert(buf[sign] == '0');
14244 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14245 buf[sign+1] == 'o');
14246 numnondigits -= 2;
14247 buf += 2;
14248 len -= 2;
14249 if (sign)
14250 buf[0] = '-';
14251 assert(len == numnondigits + numdigits);
14252 assert(numdigits > 0);
14253 }
14254
14255 /* Fill with leading zeroes to meet minimum width. */
14256 if (prec > numdigits) {
14257 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14258 numnondigits + prec);
14259 char *b1;
14260 if (!r1) {
14261 Py_DECREF(result);
14262 return NULL;
14263 }
14264 b1 = PyBytes_AS_STRING(r1);
14265 for (i = 0; i < numnondigits; ++i)
14266 *b1++ = *buf++;
14267 for (i = 0; i < prec - numdigits; i++)
14268 *b1++ = '0';
14269 for (i = 0; i < numdigits; i++)
14270 *b1++ = *buf++;
14271 *b1 = '\0';
14272 Py_DECREF(result);
14273 result = r1;
14274 buf = PyBytes_AS_STRING(result);
14275 len = numnondigits + prec;
14276 }
14277
14278 /* Fix up case for hex conversions. */
14279 if (type == 'X') {
14280 /* Need to convert all lower case letters to upper case.
14281 and need to convert 0x to 0X (and -0x to -0X). */
14282 for (i = 0; i < len; i++)
14283 if (buf[i] >= 'a' && buf[i] <= 'x')
14284 buf[i] -= 'a'-'A';
14285 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014286 if (!PyUnicode_Check(result)
14287 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014288 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014289 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014290 Py_DECREF(result);
14291 result = unicode;
14292 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014293 else if (len != PyUnicode_GET_LENGTH(result)) {
14294 if (PyUnicode_Resize(&result, len) < 0)
14295 Py_CLEAR(result);
14296 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014297 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014298}
14299
Ethan Furmandf3ed242014-01-05 06:50:30 -080014300/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014301 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014302 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014303 * -1 and raise an exception on error */
14304static int
Victor Stinnera47082312012-10-04 02:19:54 +020014305mainformatlong(PyObject *v,
14306 struct unicode_format_arg_t *arg,
14307 PyObject **p_output,
14308 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014309{
14310 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014311 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014312
14313 if (!PyNumber_Check(v))
14314 goto wrongtype;
14315
Ethan Furman9ab74802014-03-21 06:38:46 -070014316 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014317 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014318 if (type == 'o' || type == 'x' || type == 'X') {
14319 iobj = PyNumber_Index(v);
14320 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014321 if (PyErr_ExceptionMatches(PyExc_TypeError))
14322 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014323 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014324 }
14325 }
14326 else {
14327 iobj = PyNumber_Long(v);
14328 if (iobj == NULL ) {
14329 if (PyErr_ExceptionMatches(PyExc_TypeError))
14330 goto wrongtype;
14331 return -1;
14332 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014333 }
14334 assert(PyLong_Check(iobj));
14335 }
14336 else {
14337 iobj = v;
14338 Py_INCREF(iobj);
14339 }
14340
14341 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014342 && arg->width == -1 && arg->prec == -1
14343 && !(arg->flags & (F_SIGN | F_BLANK))
14344 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014345 {
14346 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014347 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014348 int base;
14349
Victor Stinnera47082312012-10-04 02:19:54 +020014350 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014351 {
14352 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014353 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014354 case 'd':
14355 case 'i':
14356 case 'u':
14357 base = 10;
14358 break;
14359 case 'o':
14360 base = 8;
14361 break;
14362 case 'x':
14363 case 'X':
14364 base = 16;
14365 break;
14366 }
14367
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014368 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14369 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014370 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014371 }
14372 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014373 return 1;
14374 }
14375
Ethan Furmanb95b5612015-01-23 20:05:18 -080014376 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014377 Py_DECREF(iobj);
14378 if (res == NULL)
14379 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014380 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014381 return 0;
14382
14383wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014384 switch(type)
14385 {
14386 case 'o':
14387 case 'x':
14388 case 'X':
14389 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014390 "%%%c format: an integer is required, "
14391 "not %.200s",
14392 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014393 break;
14394 default:
14395 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014396 "%%%c format: a number is required, "
14397 "not %.200s",
14398 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014399 break;
14400 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014401 return -1;
14402}
14403
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014404static Py_UCS4
14405formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014406{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014407 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014408 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014409 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014410 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014411 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014412 goto onError;
14413 }
14414 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014415 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014416 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014417 /* make sure number is a type of integer */
14418 if (!PyLong_Check(v)) {
14419 iobj = PyNumber_Index(v);
14420 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014421 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014422 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014423 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014424 Py_DECREF(iobj);
14425 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014426 else {
14427 x = PyLong_AsLong(v);
14428 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014429 if (x == -1 && PyErr_Occurred())
14430 goto onError;
14431
Victor Stinner8faf8212011-12-08 22:14:11 +010014432 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014433 PyErr_SetString(PyExc_OverflowError,
14434 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014435 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014436 }
14437
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014438 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014439 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014440
Benjamin Peterson29060642009-01-31 22:14:21 +000014441 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014442 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014443 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014444 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014445}
14446
Victor Stinnera47082312012-10-04 02:19:54 +020014447/* Parse options of an argument: flags, width, precision.
14448 Handle also "%(name)" syntax.
14449
14450 Return 0 if the argument has been formatted into arg->str.
14451 Return 1 if the argument has been written into ctx->writer,
14452 Raise an exception and return -1 on error. */
14453static int
14454unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14455 struct unicode_format_arg_t *arg)
14456{
14457#define FORMAT_READ(ctx) \
14458 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14459
14460 PyObject *v;
14461
Victor Stinnera47082312012-10-04 02:19:54 +020014462 if (arg->ch == '(') {
14463 /* Get argument value from a dictionary. Example: "%(name)s". */
14464 Py_ssize_t keystart;
14465 Py_ssize_t keylen;
14466 PyObject *key;
14467 int pcount = 1;
14468
14469 if (ctx->dict == NULL) {
14470 PyErr_SetString(PyExc_TypeError,
14471 "format requires a mapping");
14472 return -1;
14473 }
14474 ++ctx->fmtpos;
14475 --ctx->fmtcnt;
14476 keystart = ctx->fmtpos;
14477 /* Skip over balanced parentheses */
14478 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14479 arg->ch = FORMAT_READ(ctx);
14480 if (arg->ch == ')')
14481 --pcount;
14482 else if (arg->ch == '(')
14483 ++pcount;
14484 ctx->fmtpos++;
14485 }
14486 keylen = ctx->fmtpos - keystart - 1;
14487 if (ctx->fmtcnt < 0 || pcount > 0) {
14488 PyErr_SetString(PyExc_ValueError,
14489 "incomplete format key");
14490 return -1;
14491 }
14492 key = PyUnicode_Substring(ctx->fmtstr,
14493 keystart, keystart + keylen);
14494 if (key == NULL)
14495 return -1;
14496 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014497 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014498 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014499 }
14500 ctx->args = PyObject_GetItem(ctx->dict, key);
14501 Py_DECREF(key);
14502 if (ctx->args == NULL)
14503 return -1;
14504 ctx->args_owned = 1;
14505 ctx->arglen = -1;
14506 ctx->argidx = -2;
14507 }
14508
14509 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014510 while (--ctx->fmtcnt >= 0) {
14511 arg->ch = FORMAT_READ(ctx);
14512 ctx->fmtpos++;
14513 switch (arg->ch) {
14514 case '-': arg->flags |= F_LJUST; continue;
14515 case '+': arg->flags |= F_SIGN; continue;
14516 case ' ': arg->flags |= F_BLANK; continue;
14517 case '#': arg->flags |= F_ALT; continue;
14518 case '0': arg->flags |= F_ZERO; continue;
14519 }
14520 break;
14521 }
14522
14523 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014524 if (arg->ch == '*') {
14525 v = unicode_format_getnextarg(ctx);
14526 if (v == NULL)
14527 return -1;
14528 if (!PyLong_Check(v)) {
14529 PyErr_SetString(PyExc_TypeError,
14530 "* wants int");
14531 return -1;
14532 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014533 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014534 if (arg->width == -1 && PyErr_Occurred())
14535 return -1;
14536 if (arg->width < 0) {
14537 arg->flags |= F_LJUST;
14538 arg->width = -arg->width;
14539 }
14540 if (--ctx->fmtcnt >= 0) {
14541 arg->ch = FORMAT_READ(ctx);
14542 ctx->fmtpos++;
14543 }
14544 }
14545 else if (arg->ch >= '0' && arg->ch <= '9') {
14546 arg->width = arg->ch - '0';
14547 while (--ctx->fmtcnt >= 0) {
14548 arg->ch = FORMAT_READ(ctx);
14549 ctx->fmtpos++;
14550 if (arg->ch < '0' || arg->ch > '9')
14551 break;
14552 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14553 mixing signed and unsigned comparison. Since arg->ch is between
14554 '0' and '9', casting to int is safe. */
14555 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14556 PyErr_SetString(PyExc_ValueError,
14557 "width too big");
14558 return -1;
14559 }
14560 arg->width = arg->width*10 + (arg->ch - '0');
14561 }
14562 }
14563
14564 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014565 if (arg->ch == '.') {
14566 arg->prec = 0;
14567 if (--ctx->fmtcnt >= 0) {
14568 arg->ch = FORMAT_READ(ctx);
14569 ctx->fmtpos++;
14570 }
14571 if (arg->ch == '*') {
14572 v = unicode_format_getnextarg(ctx);
14573 if (v == NULL)
14574 return -1;
14575 if (!PyLong_Check(v)) {
14576 PyErr_SetString(PyExc_TypeError,
14577 "* wants int");
14578 return -1;
14579 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014580 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014581 if (arg->prec == -1 && PyErr_Occurred())
14582 return -1;
14583 if (arg->prec < 0)
14584 arg->prec = 0;
14585 if (--ctx->fmtcnt >= 0) {
14586 arg->ch = FORMAT_READ(ctx);
14587 ctx->fmtpos++;
14588 }
14589 }
14590 else if (arg->ch >= '0' && arg->ch <= '9') {
14591 arg->prec = arg->ch - '0';
14592 while (--ctx->fmtcnt >= 0) {
14593 arg->ch = FORMAT_READ(ctx);
14594 ctx->fmtpos++;
14595 if (arg->ch < '0' || arg->ch > '9')
14596 break;
14597 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14598 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014599 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014600 return -1;
14601 }
14602 arg->prec = arg->prec*10 + (arg->ch - '0');
14603 }
14604 }
14605 }
14606
14607 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14608 if (ctx->fmtcnt >= 0) {
14609 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14610 if (--ctx->fmtcnt >= 0) {
14611 arg->ch = FORMAT_READ(ctx);
14612 ctx->fmtpos++;
14613 }
14614 }
14615 }
14616 if (ctx->fmtcnt < 0) {
14617 PyErr_SetString(PyExc_ValueError,
14618 "incomplete format");
14619 return -1;
14620 }
14621 return 0;
14622
14623#undef FORMAT_READ
14624}
14625
14626/* Format one argument. Supported conversion specifiers:
14627
14628 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014629 - "i", "d", "u": int or float
14630 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014631 - "e", "E", "f", "F", "g", "G": float
14632 - "c": int or str (1 character)
14633
Victor Stinner8dbd4212012-12-04 09:30:24 +010014634 When possible, the output is written directly into the Unicode writer
14635 (ctx->writer). A string is created when padding is required.
14636
Victor Stinnera47082312012-10-04 02:19:54 +020014637 Return 0 if the argument has been formatted into *p_str,
14638 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014639 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014640static int
14641unicode_format_arg_format(struct unicode_formatter_t *ctx,
14642 struct unicode_format_arg_t *arg,
14643 PyObject **p_str)
14644{
14645 PyObject *v;
14646 _PyUnicodeWriter *writer = &ctx->writer;
14647
14648 if (ctx->fmtcnt == 0)
14649 ctx->writer.overallocate = 0;
14650
Victor Stinnera47082312012-10-04 02:19:54 +020014651 v = unicode_format_getnextarg(ctx);
14652 if (v == NULL)
14653 return -1;
14654
Victor Stinnera47082312012-10-04 02:19:54 +020014655
14656 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014657 case 's':
14658 case 'r':
14659 case 'a':
14660 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14661 /* Fast path */
14662 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14663 return -1;
14664 return 1;
14665 }
14666
14667 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14668 *p_str = v;
14669 Py_INCREF(*p_str);
14670 }
14671 else {
14672 if (arg->ch == 's')
14673 *p_str = PyObject_Str(v);
14674 else if (arg->ch == 'r')
14675 *p_str = PyObject_Repr(v);
14676 else
14677 *p_str = PyObject_ASCII(v);
14678 }
14679 break;
14680
14681 case 'i':
14682 case 'd':
14683 case 'u':
14684 case 'o':
14685 case 'x':
14686 case 'X':
14687 {
14688 int ret = mainformatlong(v, arg, p_str, writer);
14689 if (ret != 0)
14690 return ret;
14691 arg->sign = 1;
14692 break;
14693 }
14694
14695 case 'e':
14696 case 'E':
14697 case 'f':
14698 case 'F':
14699 case 'g':
14700 case 'G':
14701 if (arg->width == -1 && arg->prec == -1
14702 && !(arg->flags & (F_SIGN | F_BLANK)))
14703 {
14704 /* Fast path */
14705 if (formatfloat(v, arg, NULL, writer) == -1)
14706 return -1;
14707 return 1;
14708 }
14709
14710 arg->sign = 1;
14711 if (formatfloat(v, arg, p_str, NULL) == -1)
14712 return -1;
14713 break;
14714
14715 case 'c':
14716 {
14717 Py_UCS4 ch = formatchar(v);
14718 if (ch == (Py_UCS4) -1)
14719 return -1;
14720 if (arg->width == -1 && arg->prec == -1) {
14721 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014722 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014723 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014724 return 1;
14725 }
14726 *p_str = PyUnicode_FromOrdinal(ch);
14727 break;
14728 }
14729
14730 default:
14731 PyErr_Format(PyExc_ValueError,
14732 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014733 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014734 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14735 (int)arg->ch,
14736 ctx->fmtpos - 1);
14737 return -1;
14738 }
14739 if (*p_str == NULL)
14740 return -1;
14741 assert (PyUnicode_Check(*p_str));
14742 return 0;
14743}
14744
14745static int
14746unicode_format_arg_output(struct unicode_formatter_t *ctx,
14747 struct unicode_format_arg_t *arg,
14748 PyObject *str)
14749{
14750 Py_ssize_t len;
14751 enum PyUnicode_Kind kind;
14752 void *pbuf;
14753 Py_ssize_t pindex;
14754 Py_UCS4 signchar;
14755 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014756 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014757 Py_ssize_t sublen;
14758 _PyUnicodeWriter *writer = &ctx->writer;
14759 Py_UCS4 fill;
14760
14761 fill = ' ';
14762 if (arg->sign && arg->flags & F_ZERO)
14763 fill = '0';
14764
14765 if (PyUnicode_READY(str) == -1)
14766 return -1;
14767
14768 len = PyUnicode_GET_LENGTH(str);
14769 if ((arg->width == -1 || arg->width <= len)
14770 && (arg->prec == -1 || arg->prec >= len)
14771 && !(arg->flags & (F_SIGN | F_BLANK)))
14772 {
14773 /* Fast path */
14774 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14775 return -1;
14776 return 0;
14777 }
14778
14779 /* Truncate the string for "s", "r" and "a" formats
14780 if the precision is set */
14781 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14782 if (arg->prec >= 0 && len > arg->prec)
14783 len = arg->prec;
14784 }
14785
14786 /* Adjust sign and width */
14787 kind = PyUnicode_KIND(str);
14788 pbuf = PyUnicode_DATA(str);
14789 pindex = 0;
14790 signchar = '\0';
14791 if (arg->sign) {
14792 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14793 if (ch == '-' || ch == '+') {
14794 signchar = ch;
14795 len--;
14796 pindex++;
14797 }
14798 else if (arg->flags & F_SIGN)
14799 signchar = '+';
14800 else if (arg->flags & F_BLANK)
14801 signchar = ' ';
14802 else
14803 arg->sign = 0;
14804 }
14805 if (arg->width < len)
14806 arg->width = len;
14807
14808 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014809 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014810 if (!(arg->flags & F_LJUST)) {
14811 if (arg->sign) {
14812 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014813 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014814 }
14815 else {
14816 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014817 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014818 }
14819 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014820 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14821 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014822 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014823 }
14824
Victor Stinnera47082312012-10-04 02:19:54 +020014825 buflen = arg->width;
14826 if (arg->sign && len == arg->width)
14827 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014828 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014829 return -1;
14830
14831 /* Write the sign if needed */
14832 if (arg->sign) {
14833 if (fill != ' ') {
14834 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14835 writer->pos += 1;
14836 }
14837 if (arg->width > len)
14838 arg->width--;
14839 }
14840
14841 /* Write the numeric prefix for "x", "X" and "o" formats
14842 if the alternate form is used.
14843 For example, write "0x" for the "%#x" format. */
14844 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14845 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14846 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14847 if (fill != ' ') {
14848 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14849 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14850 writer->pos += 2;
14851 pindex += 2;
14852 }
14853 arg->width -= 2;
14854 if (arg->width < 0)
14855 arg->width = 0;
14856 len -= 2;
14857 }
14858
14859 /* Pad left with the fill character if needed */
14860 if (arg->width > len && !(arg->flags & F_LJUST)) {
14861 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014862 unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014863 writer->pos += sublen;
14864 arg->width = len;
14865 }
14866
14867 /* If padding with spaces: write sign if needed and/or numeric prefix if
14868 the alternate form is used */
14869 if (fill == ' ') {
14870 if (arg->sign) {
14871 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14872 writer->pos += 1;
14873 }
14874 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14875 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14876 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14877 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14878 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14879 writer->pos += 2;
14880 pindex += 2;
14881 }
14882 }
14883
14884 /* Write characters */
14885 if (len) {
14886 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14887 str, pindex, len);
14888 writer->pos += len;
14889 }
14890
14891 /* Pad right with the fill character if needed */
14892 if (arg->width > len) {
14893 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014894 unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014895 writer->pos += sublen;
14896 }
14897 return 0;
14898}
14899
14900/* Helper of PyUnicode_Format(): format one arg.
14901 Return 0 on success, raise an exception and return -1 on error. */
14902static int
14903unicode_format_arg(struct unicode_formatter_t *ctx)
14904{
14905 struct unicode_format_arg_t arg;
14906 PyObject *str;
14907 int ret;
14908
Victor Stinner8dbd4212012-12-04 09:30:24 +010014909 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014910 if (arg.ch == '%') {
14911 ctx->fmtpos++;
14912 ctx->fmtcnt--;
14913 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14914 return -1;
14915 return 0;
14916 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014917 arg.flags = 0;
14918 arg.width = -1;
14919 arg.prec = -1;
14920 arg.sign = 0;
14921 str = NULL;
14922
Victor Stinnera47082312012-10-04 02:19:54 +020014923 ret = unicode_format_arg_parse(ctx, &arg);
14924 if (ret == -1)
14925 return -1;
14926
14927 ret = unicode_format_arg_format(ctx, &arg, &str);
14928 if (ret == -1)
14929 return -1;
14930
14931 if (ret != 1) {
14932 ret = unicode_format_arg_output(ctx, &arg, str);
14933 Py_DECREF(str);
14934 if (ret == -1)
14935 return -1;
14936 }
14937
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014938 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014939 PyErr_SetString(PyExc_TypeError,
14940 "not all arguments converted during string formatting");
14941 return -1;
14942 }
14943 return 0;
14944}
14945
Alexander Belopolsky40018472011-02-26 01:02:56 +000014946PyObject *
14947PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014948{
Victor Stinnera47082312012-10-04 02:19:54 +020014949 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014950
Guido van Rossumd57fd912000-03-10 22:53:23 +000014951 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014952 PyErr_BadInternalCall();
14953 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014954 }
Victor Stinnera47082312012-10-04 02:19:54 +020014955
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014956 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014957 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014958
14959 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014960 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14961 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14962 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14963 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014964
Victor Stinner8f674cc2013-04-17 23:02:17 +020014965 _PyUnicodeWriter_Init(&ctx.writer);
14966 ctx.writer.min_length = ctx.fmtcnt + 100;
14967 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014968
Guido van Rossumd57fd912000-03-10 22:53:23 +000014969 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014970 ctx.arglen = PyTuple_Size(args);
14971 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014972 }
14973 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014974 ctx.arglen = -1;
14975 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014976 }
Victor Stinnera47082312012-10-04 02:19:54 +020014977 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014978 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014979 ctx.dict = args;
14980 else
14981 ctx.dict = NULL;
14982 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014983
Victor Stinnera47082312012-10-04 02:19:54 +020014984 while (--ctx.fmtcnt >= 0) {
14985 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014986 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014987
14988 nonfmtpos = ctx.fmtpos++;
14989 while (ctx.fmtcnt >= 0 &&
14990 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14991 ctx.fmtpos++;
14992 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014993 }
Victor Stinnera47082312012-10-04 02:19:54 +020014994 if (ctx.fmtcnt < 0) {
14995 ctx.fmtpos--;
14996 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014997 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014998
Victor Stinnercfc4c132013-04-03 01:48:39 +020014999 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
15000 nonfmtpos, ctx.fmtpos) < 0)
15001 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015002 }
15003 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015004 ctx.fmtpos++;
15005 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000015006 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020015007 }
15008 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020015009
Victor Stinnera47082312012-10-04 02:19:54 +020015010 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015011 PyErr_SetString(PyExc_TypeError,
15012 "not all arguments converted during string formatting");
15013 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015014 }
15015
Victor Stinnera47082312012-10-04 02:19:54 +020015016 if (ctx.args_owned) {
15017 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015018 }
Victor Stinnera47082312012-10-04 02:19:54 +020015019 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015020
Benjamin Peterson29060642009-01-31 22:14:21 +000015021 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020015022 _PyUnicodeWriter_Dealloc(&ctx.writer);
15023 if (ctx.args_owned) {
15024 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015025 }
15026 return NULL;
15027}
15028
Jeremy Hylton938ace62002-07-17 16:30:39 +000015029static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000015030unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
15031
Tim Peters6d6c1a32001-08-02 04:15:00 +000015032static PyObject *
15033unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15034{
Benjamin Peterson29060642009-01-31 22:14:21 +000015035 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015036 static char *kwlist[] = {"object", "encoding", "errors", 0};
15037 char *encoding = NULL;
15038 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015039
Benjamin Peterson14339b62009-01-31 16:36:08 +000015040 if (type != &PyUnicode_Type)
15041 return unicode_subtype_new(type, args, kwds);
15042 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015043 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015044 return NULL;
15045 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015046 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015047 if (encoding == NULL && errors == NULL)
15048 return PyObject_Str(x);
15049 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015050 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015051}
15052
Guido van Rossume023fe02001-08-30 03:12:59 +000015053static PyObject *
15054unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15055{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015056 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015057 Py_ssize_t length, char_size;
15058 int share_wstr, share_utf8;
15059 unsigned int kind;
15060 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015061
Benjamin Peterson14339b62009-01-31 16:36:08 +000015062 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015063
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015064 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015065 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015066 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015067 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015068 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015069 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015070 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015071 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015072
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015073 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015074 if (self == NULL) {
15075 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015076 return NULL;
15077 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015078 kind = PyUnicode_KIND(unicode);
15079 length = PyUnicode_GET_LENGTH(unicode);
15080
15081 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015082#ifdef Py_DEBUG
15083 _PyUnicode_HASH(self) = -1;
15084#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015085 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015086#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015087 _PyUnicode_STATE(self).interned = 0;
15088 _PyUnicode_STATE(self).kind = kind;
15089 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015090 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015091 _PyUnicode_STATE(self).ready = 1;
15092 _PyUnicode_WSTR(self) = NULL;
15093 _PyUnicode_UTF8_LENGTH(self) = 0;
15094 _PyUnicode_UTF8(self) = NULL;
15095 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015096 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015097
15098 share_utf8 = 0;
15099 share_wstr = 0;
15100 if (kind == PyUnicode_1BYTE_KIND) {
15101 char_size = 1;
15102 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15103 share_utf8 = 1;
15104 }
15105 else if (kind == PyUnicode_2BYTE_KIND) {
15106 char_size = 2;
15107 if (sizeof(wchar_t) == 2)
15108 share_wstr = 1;
15109 }
15110 else {
15111 assert(kind == PyUnicode_4BYTE_KIND);
15112 char_size = 4;
15113 if (sizeof(wchar_t) == 4)
15114 share_wstr = 1;
15115 }
15116
15117 /* Ensure we won't overflow the length. */
15118 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15119 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015120 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015121 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015122 data = PyObject_MALLOC((length + 1) * char_size);
15123 if (data == NULL) {
15124 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015125 goto onError;
15126 }
15127
Victor Stinnerc3c74152011-10-02 20:39:55 +020015128 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015129 if (share_utf8) {
15130 _PyUnicode_UTF8_LENGTH(self) = length;
15131 _PyUnicode_UTF8(self) = data;
15132 }
15133 if (share_wstr) {
15134 _PyUnicode_WSTR_LENGTH(self) = length;
15135 _PyUnicode_WSTR(self) = (wchar_t *)data;
15136 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015137
Christian Heimesf051e432016-09-13 20:22:02 +020015138 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015139 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015140 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015141#ifdef Py_DEBUG
15142 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15143#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015144 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015145 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015146
15147onError:
15148 Py_DECREF(unicode);
15149 Py_DECREF(self);
15150 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015151}
15152
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015153PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015154"str(object='') -> str\n\
15155str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015156\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015157Create a new string object from the given object. If encoding or\n\
15158errors is specified, then the object must expose a data buffer\n\
15159that will be decoded using the given encoding and error handler.\n\
15160Otherwise, returns the result of object.__str__() (if defined)\n\
15161or repr(object).\n\
15162encoding defaults to sys.getdefaultencoding().\n\
15163errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015164
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015165static PyObject *unicode_iter(PyObject *seq);
15166
Guido van Rossumd57fd912000-03-10 22:53:23 +000015167PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015168 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015169 "str", /* tp_name */
15170 sizeof(PyUnicodeObject), /* tp_basicsize */
15171 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015172 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015173 (destructor)unicode_dealloc, /* tp_dealloc */
15174 0, /* tp_print */
15175 0, /* tp_getattr */
15176 0, /* tp_setattr */
15177 0, /* tp_reserved */
15178 unicode_repr, /* tp_repr */
15179 &unicode_as_number, /* tp_as_number */
15180 &unicode_as_sequence, /* tp_as_sequence */
15181 &unicode_as_mapping, /* tp_as_mapping */
15182 (hashfunc) unicode_hash, /* tp_hash*/
15183 0, /* tp_call*/
15184 (reprfunc) unicode_str, /* tp_str */
15185 PyObject_GenericGetAttr, /* tp_getattro */
15186 0, /* tp_setattro */
15187 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015188 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015189 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15190 unicode_doc, /* tp_doc */
15191 0, /* tp_traverse */
15192 0, /* tp_clear */
15193 PyUnicode_RichCompare, /* tp_richcompare */
15194 0, /* tp_weaklistoffset */
15195 unicode_iter, /* tp_iter */
15196 0, /* tp_iternext */
15197 unicode_methods, /* tp_methods */
15198 0, /* tp_members */
15199 0, /* tp_getset */
15200 &PyBaseObject_Type, /* tp_base */
15201 0, /* tp_dict */
15202 0, /* tp_descr_get */
15203 0, /* tp_descr_set */
15204 0, /* tp_dictoffset */
15205 0, /* tp_init */
15206 0, /* tp_alloc */
15207 unicode_new, /* tp_new */
15208 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015209};
15210
15211/* Initialize the Unicode implementation */
15212
Victor Stinner3a50e702011-10-18 21:21:00 +020015213int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015214{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015215 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015216 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015217 0x000A, /* LINE FEED */
15218 0x000D, /* CARRIAGE RETURN */
15219 0x001C, /* FILE SEPARATOR */
15220 0x001D, /* GROUP SEPARATOR */
15221 0x001E, /* RECORD SEPARATOR */
15222 0x0085, /* NEXT LINE */
15223 0x2028, /* LINE SEPARATOR */
15224 0x2029, /* PARAGRAPH SEPARATOR */
15225 };
15226
Fred Drakee4315f52000-05-09 19:53:39 +000015227 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015228 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015229 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015230 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015231 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015232
Guido van Rossumcacfc072002-05-24 19:01:59 +000015233 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015234 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015235
15236 /* initialize the linebreak bloom filter */
15237 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015238 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015239 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015240
Christian Heimes26532f72013-07-20 14:57:16 +020015241 if (PyType_Ready(&EncodingMapType) < 0)
15242 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015243
Benjamin Petersonc4311282012-10-30 23:21:10 -040015244 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15245 Py_FatalError("Can't initialize field name iterator type");
15246
15247 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15248 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015249
Victor Stinner3a50e702011-10-18 21:21:00 +020015250 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015251}
15252
15253/* Finalize the Unicode implementation */
15254
Christian Heimesa156e092008-02-16 07:38:31 +000015255int
15256PyUnicode_ClearFreeList(void)
15257{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015258 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015259}
15260
Guido van Rossumd57fd912000-03-10 22:53:23 +000015261void
Thomas Wouters78890102000-07-22 19:25:51 +000015262_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015263{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015264 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015265
Serhiy Storchaka05997252013-01-26 12:14:02 +020015266 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015267
Serhiy Storchaka05997252013-01-26 12:14:02 +020015268 for (i = 0; i < 256; i++)
15269 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015270 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015271 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015272}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015273
Walter Dörwald16807132007-05-25 13:52:07 +000015274void
15275PyUnicode_InternInPlace(PyObject **p)
15276{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015277 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015278 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015279#ifdef Py_DEBUG
15280 assert(s != NULL);
15281 assert(_PyUnicode_CHECK(s));
15282#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015283 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015284 return;
15285#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015286 /* If it's a subclass, we don't really know what putting
15287 it in the interned dict might do. */
15288 if (!PyUnicode_CheckExact(s))
15289 return;
15290 if (PyUnicode_CHECK_INTERNED(s))
15291 return;
15292 if (interned == NULL) {
15293 interned = PyDict_New();
15294 if (interned == NULL) {
15295 PyErr_Clear(); /* Don't leave an exception */
15296 return;
15297 }
15298 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015299 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015300 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015301 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015302 if (t == NULL) {
15303 PyErr_Clear();
15304 return;
15305 }
15306 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015307 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015308 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015309 return;
15310 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015311 /* The two references in interned are not counted by refcnt.
15312 The deallocator will take care of this */
15313 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015314 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015315}
15316
15317void
15318PyUnicode_InternImmortal(PyObject **p)
15319{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015320 PyUnicode_InternInPlace(p);
15321 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015322 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015323 Py_INCREF(*p);
15324 }
Walter Dörwald16807132007-05-25 13:52:07 +000015325}
15326
15327PyObject *
15328PyUnicode_InternFromString(const char *cp)
15329{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015330 PyObject *s = PyUnicode_FromString(cp);
15331 if (s == NULL)
15332 return NULL;
15333 PyUnicode_InternInPlace(&s);
15334 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015335}
15336
Alexander Belopolsky40018472011-02-26 01:02:56 +000015337void
15338_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015339{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015340 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015341 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015342 Py_ssize_t i, n;
15343 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015344
Benjamin Peterson14339b62009-01-31 16:36:08 +000015345 if (interned == NULL || !PyDict_Check(interned))
15346 return;
15347 keys = PyDict_Keys(interned);
15348 if (keys == NULL || !PyList_Check(keys)) {
15349 PyErr_Clear();
15350 return;
15351 }
Walter Dörwald16807132007-05-25 13:52:07 +000015352
Benjamin Peterson14339b62009-01-31 16:36:08 +000015353 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15354 detector, interned unicode strings are not forcibly deallocated;
15355 rather, we give them their stolen references back, and then clear
15356 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015357
Benjamin Peterson14339b62009-01-31 16:36:08 +000015358 n = PyList_GET_SIZE(keys);
15359 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015360 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015361 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015362 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015363 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015364 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015365 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015366 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015367 case SSTATE_NOT_INTERNED:
15368 /* XXX Shouldn't happen */
15369 break;
15370 case SSTATE_INTERNED_IMMORTAL:
15371 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015372 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015373 break;
15374 case SSTATE_INTERNED_MORTAL:
15375 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015376 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015377 break;
15378 default:
15379 Py_FatalError("Inconsistent interned string state.");
15380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015381 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015382 }
15383 fprintf(stderr, "total size of all interned strings: "
15384 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15385 "mortal/immortal\n", mortal_size, immortal_size);
15386 Py_DECREF(keys);
15387 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015388 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015389}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015390
15391
15392/********************* Unicode Iterator **************************/
15393
15394typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015395 PyObject_HEAD
15396 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015397 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015398} unicodeiterobject;
15399
15400static void
15401unicodeiter_dealloc(unicodeiterobject *it)
15402{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015403 _PyObject_GC_UNTRACK(it);
15404 Py_XDECREF(it->it_seq);
15405 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015406}
15407
15408static int
15409unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15410{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015411 Py_VISIT(it->it_seq);
15412 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015413}
15414
15415static PyObject *
15416unicodeiter_next(unicodeiterobject *it)
15417{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015418 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015419
Benjamin Peterson14339b62009-01-31 16:36:08 +000015420 assert(it != NULL);
15421 seq = it->it_seq;
15422 if (seq == NULL)
15423 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015424 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015426 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15427 int kind = PyUnicode_KIND(seq);
15428 void *data = PyUnicode_DATA(seq);
15429 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15430 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015431 if (item != NULL)
15432 ++it->it_index;
15433 return item;
15434 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015435
Benjamin Peterson14339b62009-01-31 16:36:08 +000015436 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015437 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015438 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015439}
15440
15441static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015442unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015443{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015444 Py_ssize_t len = 0;
15445 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015446 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015447 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015448}
15449
15450PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15451
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015452static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015453unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015454{
15455 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015456 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015457 it->it_seq, it->it_index);
15458 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015459 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015460 if (u == NULL)
15461 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015462 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015463 }
15464}
15465
15466PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15467
15468static PyObject *
15469unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15470{
15471 Py_ssize_t index = PyLong_AsSsize_t(state);
15472 if (index == -1 && PyErr_Occurred())
15473 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015474 if (it->it_seq != NULL) {
15475 if (index < 0)
15476 index = 0;
15477 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15478 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15479 it->it_index = index;
15480 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015481 Py_RETURN_NONE;
15482}
15483
15484PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15485
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015486static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015487 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015488 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015489 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15490 reduce_doc},
15491 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15492 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015493 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015494};
15495
15496PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015497 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15498 "str_iterator", /* tp_name */
15499 sizeof(unicodeiterobject), /* tp_basicsize */
15500 0, /* tp_itemsize */
15501 /* methods */
15502 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15503 0, /* tp_print */
15504 0, /* tp_getattr */
15505 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015506 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015507 0, /* tp_repr */
15508 0, /* tp_as_number */
15509 0, /* tp_as_sequence */
15510 0, /* tp_as_mapping */
15511 0, /* tp_hash */
15512 0, /* tp_call */
15513 0, /* tp_str */
15514 PyObject_GenericGetAttr, /* tp_getattro */
15515 0, /* tp_setattro */
15516 0, /* tp_as_buffer */
15517 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15518 0, /* tp_doc */
15519 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15520 0, /* tp_clear */
15521 0, /* tp_richcompare */
15522 0, /* tp_weaklistoffset */
15523 PyObject_SelfIter, /* tp_iter */
15524 (iternextfunc)unicodeiter_next, /* tp_iternext */
15525 unicodeiter_methods, /* tp_methods */
15526 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015527};
15528
15529static PyObject *
15530unicode_iter(PyObject *seq)
15531{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015532 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015533
Benjamin Peterson14339b62009-01-31 16:36:08 +000015534 if (!PyUnicode_Check(seq)) {
15535 PyErr_BadInternalCall();
15536 return NULL;
15537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015538 if (PyUnicode_READY(seq) == -1)
15539 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015540 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15541 if (it == NULL)
15542 return NULL;
15543 it->it_index = 0;
15544 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015545 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015546 _PyObject_GC_TRACK(it);
15547 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015548}
15549
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015550
15551size_t
15552Py_UNICODE_strlen(const Py_UNICODE *u)
15553{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015554 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015555}
15556
15557Py_UNICODE*
15558Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15559{
15560 Py_UNICODE *u = s1;
15561 while ((*u++ = *s2++));
15562 return s1;
15563}
15564
15565Py_UNICODE*
15566Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15567{
15568 Py_UNICODE *u = s1;
15569 while ((*u++ = *s2++))
15570 if (n-- == 0)
15571 break;
15572 return s1;
15573}
15574
15575Py_UNICODE*
15576Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15577{
15578 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015579 u1 += wcslen(u1);
15580 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015581 return s1;
15582}
15583
15584int
15585Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15586{
15587 while (*s1 && *s2 && *s1 == *s2)
15588 s1++, s2++;
15589 if (*s1 && *s2)
15590 return (*s1 < *s2) ? -1 : +1;
15591 if (*s1)
15592 return 1;
15593 if (*s2)
15594 return -1;
15595 return 0;
15596}
15597
15598int
15599Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15600{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015601 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015602 for (; n != 0; n--) {
15603 u1 = *s1;
15604 u2 = *s2;
15605 if (u1 != u2)
15606 return (u1 < u2) ? -1 : +1;
15607 if (u1 == '\0')
15608 return 0;
15609 s1++;
15610 s2++;
15611 }
15612 return 0;
15613}
15614
15615Py_UNICODE*
15616Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15617{
15618 const Py_UNICODE *p;
15619 for (p = s; *p; p++)
15620 if (*p == c)
15621 return (Py_UNICODE*)p;
15622 return NULL;
15623}
15624
15625Py_UNICODE*
15626Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15627{
15628 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015629 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015630 while (p != s) {
15631 p--;
15632 if (*p == c)
15633 return (Py_UNICODE*)p;
15634 }
15635 return NULL;
15636}
Victor Stinner331ea922010-08-10 16:37:20 +000015637
Victor Stinner71133ff2010-09-01 23:43:53 +000015638Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015639PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015640{
Victor Stinner577db2c2011-10-11 22:12:48 +020015641 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015642 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015643
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015644 if (!PyUnicode_Check(unicode)) {
15645 PyErr_BadArgument();
15646 return NULL;
15647 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015648 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015649 if (u == NULL)
15650 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015651 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015652 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015653 PyErr_NoMemory();
15654 return NULL;
15655 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015656 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015657 size *= sizeof(Py_UNICODE);
15658 copy = PyMem_Malloc(size);
15659 if (copy == NULL) {
15660 PyErr_NoMemory();
15661 return NULL;
15662 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015663 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015664 return copy;
15665}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015666
Georg Brandl66c221e2010-10-14 07:04:07 +000015667/* A _string module, to export formatter_parser and formatter_field_name_split
15668 to the string.Formatter class implemented in Python. */
15669
15670static PyMethodDef _string_methods[] = {
15671 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15672 METH_O, PyDoc_STR("split the argument as a field name")},
15673 {"formatter_parser", (PyCFunction) formatter_parser,
15674 METH_O, PyDoc_STR("parse the argument as a format string")},
15675 {NULL, NULL}
15676};
15677
15678static struct PyModuleDef _string_module = {
15679 PyModuleDef_HEAD_INIT,
15680 "_string",
15681 PyDoc_STR("string helper module"),
15682 0,
15683 _string_methods,
15684 NULL,
15685 NULL,
15686 NULL,
15687 NULL
15688};
15689
15690PyMODINIT_FUNC
15691PyInit__string(void)
15692{
15693 return PyModule_Create(&_string_module);
15694}
15695
15696
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015697#ifdef __cplusplus
15698}
15699#endif