blob: 1351eece8e920bacacb98b559e0df92961e2e3a4 [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: {
Victor Stinner163403a2018-11-27 12:41:17 +0100231 assert(value <= 0xff);
Victor Stinner59423e32018-11-26 13:40:01 +0100232 Py_UCS1 ch = (unsigned char)value;
233 Py_UCS1 *to = (Py_UCS1 *)data + start;
234 memset(to, ch, length);
235 break;
236 }
237 case PyUnicode_2BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100238 assert(value <= 0xffff);
Victor Stinner59423e32018-11-26 13:40:01 +0100239 Py_UCS2 ch = (Py_UCS2)value;
240 Py_UCS2 *to = (Py_UCS2 *)data + start;
241 const Py_UCS2 *end = to + length;
242 for (; to < end; ++to) *to = ch;
243 break;
244 }
245 case PyUnicode_4BYTE_KIND: {
Victor Stinner163403a2018-11-27 12:41:17 +0100246 assert(value <= MAX_UNICODE);
Victor Stinner59423e32018-11-26 13:40:01 +0100247 Py_UCS4 ch = value;
248 Py_UCS4 * to = (Py_UCS4 *)data + start;
249 const Py_UCS4 *end = to + length;
250 for (; to < end; ++to) *to = ch;
251 break;
252 }
253 default: Py_UNREACHABLE();
254 }
255}
256
257
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200258/* Forward declaration */
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700259static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +0200260_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
261
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200262/* List of static strings. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200263static _Py_Identifier *static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200264
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000265/* Single character Unicode strings in the Latin-1 range are being
266 shared as well. */
Serhiy Storchaka678db842013-01-26 12:16:36 +0200267static PyObject *unicode_latin1[256] = {NULL};
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000268
Christian Heimes190d79e2008-01-30 11:58:22 +0000269/* Fast detection of the most frequent whitespace characters */
270const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000271 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000272/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000273/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000274/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000275/* case 0x000C: * FORM FEED */
276/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000277 0, 1, 1, 1, 1, 1, 0, 0,
278 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000279/* case 0x001C: * FILE SEPARATOR */
280/* case 0x001D: * GROUP SEPARATOR */
281/* case 0x001E: * RECORD SEPARATOR */
282/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000283 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000284/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 1, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000289
Benjamin Peterson14339b62009-01-31 16:36:08 +0000290 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,
295 0, 0, 0, 0, 0, 0, 0, 0,
296 0, 0, 0, 0, 0, 0, 0, 0,
297 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000298};
299
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200300/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200301static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200302static PyObject* get_latin1_char(unsigned char ch);
Victor Stinner488fa492011-12-12 00:01:39 +0100303static int unicode_modifiable(PyObject *unicode);
304
Victor Stinnerfe226c02011-10-03 03:52:20 +0200305
Alexander Belopolsky40018472011-02-26 01:02:56 +0000306static PyObject *
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100307_PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200308static PyObject *
309_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
310static PyObject *
311_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
312
313static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000314unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000315 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100316 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000317 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
318
Alexander Belopolsky40018472011-02-26 01:02:56 +0000319static void
320raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300321 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100322 PyObject *unicode,
323 Py_ssize_t startpos, Py_ssize_t endpos,
324 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000325
Christian Heimes190d79e2008-01-30 11:58:22 +0000326/* Same for linebreaks */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200327static const unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000328 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000329/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000330/* 0x000B, * LINE TABULATION */
331/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000332/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000333 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000334 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000335/* 0x001C, * FILE SEPARATOR */
336/* 0x001D, * GROUP SEPARATOR */
337/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000338 0, 0, 0, 0, 1, 1, 1, 0,
339 0, 0, 0, 0, 0, 0, 0, 0,
340 0, 0, 0, 0, 0, 0, 0, 0,
341 0, 0, 0, 0, 0, 0, 0, 0,
342 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000343
Benjamin Peterson14339b62009-01-31 16:36:08 +0000344 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,
349 0, 0, 0, 0, 0, 0, 0, 0,
350 0, 0, 0, 0, 0, 0, 0, 0,
351 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000352};
353
INADA Naoki3ae20562017-01-16 20:41:20 +0900354static int convert_uc(PyObject *obj, void *addr);
355
Serhiy Storchaka1009bf12015-04-03 23:53:51 +0300356#include "clinic/unicodeobject.c.h"
357
Victor Stinner3d4226a2018-08-29 22:21:32 +0200358_Py_error_handler
359_Py_GetErrorHandler(const char *errors)
Victor Stinner50149202015-09-22 00:26:54 +0200360{
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200361 if (errors == NULL || strcmp(errors, "strict") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200362 return _Py_ERROR_STRICT;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200363 }
364 if (strcmp(errors, "surrogateescape") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200365 return _Py_ERROR_SURROGATEESCAPE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200366 }
367 if (strcmp(errors, "replace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200368 return _Py_ERROR_REPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200369 }
370 if (strcmp(errors, "ignore") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200371 return _Py_ERROR_IGNORE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200372 }
373 if (strcmp(errors, "backslashreplace") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200374 return _Py_ERROR_BACKSLASHREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200375 }
376 if (strcmp(errors, "surrogatepass") == 0) {
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200377 return _Py_ERROR_SURROGATEPASS;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200378 }
379 if (strcmp(errors, "xmlcharrefreplace") == 0) {
Victor Stinner50149202015-09-22 00:26:54 +0200380 return _Py_ERROR_XMLCHARREFREPLACE;
Victor Stinner1a05d6c2016-09-02 12:12:23 +0200381 }
Victor Stinner50149202015-09-22 00:26:54 +0200382 return _Py_ERROR_OTHER;
383}
384
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300385/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
386 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000387Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000388PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000389{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000390#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000391 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000392#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000393 /* This is actually an illegal character, so it should
394 not be passed to unichr. */
395 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000396#endif
397}
398
Victor Stinner910337b2011-10-03 03:20:16 +0200399#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200400int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100401_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200402{
Victor Stinner50fe3f82018-10-26 18:47:15 +0200403#define ASSERT(expr) _PyObject_ASSERT(op, (expr))
404
Victor Stinner910337b2011-10-03 03:20:16 +0200405 PyASCIIObject *ascii;
406 unsigned int kind;
407
Victor Stinner50fe3f82018-10-26 18:47:15 +0200408 ASSERT(PyUnicode_Check(op));
Victor Stinner910337b2011-10-03 03:20:16 +0200409
410 ascii = (PyASCIIObject *)op;
411 kind = ascii->state.kind;
412
Victor Stinnera3b334d2011-10-03 13:53:37 +0200413 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200414 ASSERT(kind == PyUnicode_1BYTE_KIND);
415 ASSERT(ascii->state.ready == 1);
Victor Stinner910337b2011-10-03 03:20:16 +0200416 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200417 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200418 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200419 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200420
Victor Stinnera41463c2011-10-04 01:05:08 +0200421 if (ascii->state.compact == 1) {
422 data = compact + 1;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200423 ASSERT(kind == PyUnicode_1BYTE_KIND
Victor Stinner910337b2011-10-03 03:20:16 +0200424 || kind == PyUnicode_2BYTE_KIND
425 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200426 ASSERT(ascii->state.ascii == 0);
427 ASSERT(ascii->state.ready == 1);
428 ASSERT (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100429 }
430 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200431 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
432
433 data = unicode->data.any;
434 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200435 ASSERT(ascii->length == 0);
436 ASSERT(ascii->hash == -1);
437 ASSERT(ascii->state.compact == 0);
438 ASSERT(ascii->state.ascii == 0);
439 ASSERT(ascii->state.ready == 0);
440 ASSERT(ascii->state.interned == SSTATE_NOT_INTERNED);
441 ASSERT(ascii->wstr != NULL);
442 ASSERT(data == NULL);
443 ASSERT(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200444 }
445 else {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200446 ASSERT(kind == PyUnicode_1BYTE_KIND
Victor Stinnera41463c2011-10-04 01:05:08 +0200447 || kind == PyUnicode_2BYTE_KIND
448 || kind == PyUnicode_4BYTE_KIND);
Victor Stinner50fe3f82018-10-26 18:47:15 +0200449 ASSERT(ascii->state.compact == 0);
450 ASSERT(ascii->state.ready == 1);
451 ASSERT(data != NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200452 if (ascii->state.ascii) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200453 ASSERT (compact->utf8 == data);
454 ASSERT (compact->utf8_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200455 }
456 else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200457 ASSERT (compact->utf8 != data);
Victor Stinnera41463c2011-10-04 01:05:08 +0200458 }
459 }
460 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200461 if (
462#if SIZEOF_WCHAR_T == 2
463 kind == PyUnicode_2BYTE_KIND
464#else
465 kind == PyUnicode_4BYTE_KIND
466#endif
467 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200468 {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200469 ASSERT(ascii->wstr == data);
470 ASSERT(compact->wstr_length == ascii->length);
Victor Stinnera41463c2011-10-04 01:05:08 +0200471 } else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200472 ASSERT(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200473 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200474
475 if (compact->utf8 == NULL)
Victor Stinner50fe3f82018-10-26 18:47:15 +0200476 ASSERT(compact->utf8_length == 0);
Victor Stinnera41463c2011-10-04 01:05:08 +0200477 if (ascii->wstr == NULL)
Victor Stinner50fe3f82018-10-26 18:47:15 +0200478 ASSERT(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200479 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200480 /* check that the best kind is used */
481 if (check_content && kind != PyUnicode_WCHAR_KIND)
482 {
483 Py_ssize_t i;
484 Py_UCS4 maxchar = 0;
Victor Stinner718fbf02012-04-26 00:39:37 +0200485 void *data;
486 Py_UCS4 ch;
487
488 data = PyUnicode_DATA(ascii);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200489 for (i=0; i < ascii->length; i++)
490 {
Victor Stinner718fbf02012-04-26 00:39:37 +0200491 ch = PyUnicode_READ(kind, data, i);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200492 if (ch > maxchar)
493 maxchar = ch;
494 }
495 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinner77faf692011-11-20 18:56:05 +0100496 if (ascii->state.ascii == 0) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200497 ASSERT(maxchar >= 128);
498 ASSERT(maxchar <= 255);
Victor Stinner77faf692011-11-20 18:56:05 +0100499 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200500 else
Victor Stinner50fe3f82018-10-26 18:47:15 +0200501 ASSERT(maxchar < 128);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200502 }
Victor Stinner77faf692011-11-20 18:56:05 +0100503 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200504 ASSERT(maxchar >= 0x100);
505 ASSERT(maxchar <= 0xFFFF);
Victor Stinner77faf692011-11-20 18:56:05 +0100506 }
507 else {
Victor Stinner50fe3f82018-10-26 18:47:15 +0200508 ASSERT(maxchar >= 0x10000);
509 ASSERT(maxchar <= MAX_UNICODE);
Victor Stinner77faf692011-11-20 18:56:05 +0100510 }
Victor Stinner50fe3f82018-10-26 18:47:15 +0200511 ASSERT(PyUnicode_READ(kind, data, ascii->length) == 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200512 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400513 return 1;
Victor Stinner50fe3f82018-10-26 18:47:15 +0200514
515#undef ASSERT
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400516}
Victor Stinner910337b2011-10-03 03:20:16 +0200517#endif
518
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100519static PyObject*
520unicode_result_wchar(PyObject *unicode)
521{
522#ifndef Py_DEBUG
523 Py_ssize_t len;
524
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100525 len = _PyUnicode_WSTR_LENGTH(unicode);
526 if (len == 0) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100527 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200528 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100529 }
530
531 if (len == 1) {
532 wchar_t ch = _PyUnicode_WSTR(unicode)[0];
Victor Stinnerd21b58c2013-02-26 00:15:54 +0100533 if ((Py_UCS4)ch < 256) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100534 PyObject *latin1_char = get_latin1_char((unsigned char)ch);
535 Py_DECREF(unicode);
536 return latin1_char;
537 }
538 }
539
540 if (_PyUnicode_Ready(unicode) < 0) {
Victor Stinneraa771272012-10-04 02:32:58 +0200541 Py_DECREF(unicode);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100542 return NULL;
543 }
544#else
Victor Stinneraa771272012-10-04 02:32:58 +0200545 assert(Py_REFCNT(unicode) == 1);
546
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100547 /* don't make the result ready in debug mode to ensure that the caller
548 makes the string ready before using it */
549 assert(_PyUnicode_CheckConsistency(unicode, 1));
550#endif
551 return unicode;
552}
553
554static PyObject*
555unicode_result_ready(PyObject *unicode)
556{
557 Py_ssize_t length;
558
559 length = PyUnicode_GET_LENGTH(unicode);
560 if (length == 0) {
561 if (unicode != unicode_empty) {
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100562 Py_DECREF(unicode);
Serhiy Storchaka678db842013-01-26 12:16:36 +0200563 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100564 }
565 return unicode_empty;
566 }
567
568 if (length == 1) {
Victor Stinner69ed0f42013-04-09 21:48:24 +0200569 void *data = PyUnicode_DATA(unicode);
570 int kind = PyUnicode_KIND(unicode);
571 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +0100572 if (ch < 256) {
573 PyObject *latin1_char = unicode_latin1[ch];
574 if (latin1_char != NULL) {
575 if (unicode != latin1_char) {
576 Py_INCREF(latin1_char);
577 Py_DECREF(unicode);
578 }
579 return latin1_char;
580 }
581 else {
582 assert(_PyUnicode_CheckConsistency(unicode, 1));
583 Py_INCREF(unicode);
584 unicode_latin1[ch] = unicode;
585 return unicode;
586 }
587 }
588 }
589
590 assert(_PyUnicode_CheckConsistency(unicode, 1));
591 return unicode;
592}
593
594static PyObject*
595unicode_result(PyObject *unicode)
596{
597 assert(_PyUnicode_CHECK(unicode));
598 if (PyUnicode_IS_READY(unicode))
599 return unicode_result_ready(unicode);
600 else
601 return unicode_result_wchar(unicode);
602}
603
Victor Stinnerc4b49542011-12-11 22:44:26 +0100604static PyObject*
605unicode_result_unchanged(PyObject *unicode)
606{
607 if (PyUnicode_CheckExact(unicode)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -0500608 if (PyUnicode_READY(unicode) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +0100609 return NULL;
610 Py_INCREF(unicode);
611 return unicode;
612 }
613 else
614 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +0100615 return _PyUnicode_Copy(unicode);
Victor Stinnerc4b49542011-12-11 22:44:26 +0100616}
617
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200618/* Implementation of the "backslashreplace" error handler for 8-bit encodings:
619 ASCII, Latin1, UTF-8, etc. */
620static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200621backslashreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200622 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
623{
Victor Stinnerad771582015-10-09 12:38:53 +0200624 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200625 Py_UCS4 ch;
626 enum PyUnicode_Kind kind;
627 void *data;
628
629 assert(PyUnicode_IS_READY(unicode));
630 kind = PyUnicode_KIND(unicode);
631 data = PyUnicode_DATA(unicode);
632
633 size = 0;
634 /* determine replacement size */
635 for (i = collstart; i < collend; ++i) {
636 Py_ssize_t incr;
637
638 ch = PyUnicode_READ(kind, data, i);
639 if (ch < 0x100)
640 incr = 2+2;
641 else if (ch < 0x10000)
642 incr = 2+4;
643 else {
644 assert(ch <= MAX_UNICODE);
Victor Stinner3fa36ff2015-10-09 03:37:11 +0200645 incr = 2+8;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200646 }
647 if (size > PY_SSIZE_T_MAX - incr) {
648 PyErr_SetString(PyExc_OverflowError,
649 "encoded result is too long for a Python string");
650 return NULL;
651 }
652 size += incr;
653 }
654
Victor Stinnerad771582015-10-09 12:38:53 +0200655 str = _PyBytesWriter_Prepare(writer, str, size);
656 if (str == NULL)
657 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200658
659 /* generate replacement */
660 for (i = collstart; i < collend; ++i) {
661 ch = PyUnicode_READ(kind, data, i);
Victor Stinner797485e2015-10-09 03:17:30 +0200662 *str++ = '\\';
663 if (ch >= 0x00010000) {
664 *str++ = 'U';
665 *str++ = Py_hexdigits[(ch>>28)&0xf];
666 *str++ = Py_hexdigits[(ch>>24)&0xf];
667 *str++ = Py_hexdigits[(ch>>20)&0xf];
668 *str++ = Py_hexdigits[(ch>>16)&0xf];
669 *str++ = Py_hexdigits[(ch>>12)&0xf];
670 *str++ = Py_hexdigits[(ch>>8)&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200671 }
Victor Stinner797485e2015-10-09 03:17:30 +0200672 else if (ch >= 0x100) {
673 *str++ = 'u';
674 *str++ = Py_hexdigits[(ch>>12)&0xf];
675 *str++ = Py_hexdigits[(ch>>8)&0xf];
676 }
677 else
678 *str++ = 'x';
679 *str++ = Py_hexdigits[(ch>>4)&0xf];
680 *str++ = Py_hexdigits[ch&0xf];
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200681 }
682 return str;
683}
684
685/* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
686 ASCII, Latin1, UTF-8, etc. */
687static char*
Victor Stinnerad771582015-10-09 12:38:53 +0200688xmlcharrefreplace(_PyBytesWriter *writer, char *str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200689 PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
690{
Victor Stinnerad771582015-10-09 12:38:53 +0200691 Py_ssize_t size, i;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200692 Py_UCS4 ch;
693 enum PyUnicode_Kind kind;
694 void *data;
695
696 assert(PyUnicode_IS_READY(unicode));
697 kind = PyUnicode_KIND(unicode);
698 data = PyUnicode_DATA(unicode);
699
700 size = 0;
701 /* determine replacement size */
702 for (i = collstart; i < collend; ++i) {
703 Py_ssize_t incr;
704
705 ch = PyUnicode_READ(kind, data, i);
706 if (ch < 10)
707 incr = 2+1+1;
708 else if (ch < 100)
709 incr = 2+2+1;
710 else if (ch < 1000)
711 incr = 2+3+1;
712 else if (ch < 10000)
713 incr = 2+4+1;
714 else if (ch < 100000)
715 incr = 2+5+1;
716 else if (ch < 1000000)
717 incr = 2+6+1;
718 else {
719 assert(ch <= MAX_UNICODE);
720 incr = 2+7+1;
721 }
722 if (size > PY_SSIZE_T_MAX - incr) {
723 PyErr_SetString(PyExc_OverflowError,
724 "encoded result is too long for a Python string");
725 return NULL;
726 }
727 size += incr;
728 }
729
Victor Stinnerad771582015-10-09 12:38:53 +0200730 str = _PyBytesWriter_Prepare(writer, str, size);
731 if (str == NULL)
732 return NULL;
Victor Stinnere7bf86c2015-10-09 01:39:28 +0200733
734 /* generate replacement */
735 for (i = collstart; i < collend; ++i) {
736 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
737 }
738 return str;
739}
740
Thomas Wouters477c8d52006-05-27 19:21:47 +0000741/* --- Bloom Filters ----------------------------------------------------- */
742
743/* stuff to implement simple "bloom filters" for Unicode characters.
744 to keep things simple, we use a single bitmask, using the least 5
745 bits from each unicode characters as the bit index. */
746
747/* the linebreak mask is set up by Unicode_Init below */
748
Antoine Pitrouf068f942010-01-13 14:19:12 +0000749#if LONG_BIT >= 128
750#define BLOOM_WIDTH 128
751#elif LONG_BIT >= 64
752#define BLOOM_WIDTH 64
753#elif LONG_BIT >= 32
754#define BLOOM_WIDTH 32
755#else
756#error "LONG_BIT is smaller than 32"
757#endif
758
Thomas Wouters477c8d52006-05-27 19:21:47 +0000759#define BLOOM_MASK unsigned long
760
Serhiy Storchaka05997252013-01-26 12:14:02 +0200761static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000762
Antoine Pitrouf068f942010-01-13 14:19:12 +0000763#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000764
Benjamin Peterson29060642009-01-31 22:14:21 +0000765#define BLOOM_LINEBREAK(ch) \
766 ((ch) < 128U ? ascii_linebreak[(ch)] : \
767 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000768
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700769static inline BLOOM_MASK
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200770make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000771{
Victor Stinnera85af502013-04-09 21:53:54 +0200772#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
773 do { \
774 TYPE *data = (TYPE *)PTR; \
775 TYPE *end = data + LEN; \
776 Py_UCS4 ch; \
777 for (; data != end; data++) { \
778 ch = *data; \
779 MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
780 } \
781 break; \
782 } while (0)
783
Thomas Wouters477c8d52006-05-27 19:21:47 +0000784 /* calculate simple bloom-style bitmask for a given unicode string */
785
Antoine Pitrouf068f942010-01-13 14:19:12 +0000786 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000787
788 mask = 0;
Victor Stinnera85af502013-04-09 21:53:54 +0200789 switch (kind) {
790 case PyUnicode_1BYTE_KIND:
791 BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
792 break;
793 case PyUnicode_2BYTE_KIND:
794 BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
795 break;
796 case PyUnicode_4BYTE_KIND:
797 BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
798 break;
799 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700800 Py_UNREACHABLE();
Victor Stinnera85af502013-04-09 21:53:54 +0200801 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000802 return mask;
Victor Stinnera85af502013-04-09 21:53:54 +0200803
804#undef BLOOM_UPDATE
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805}
806
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300807static int
808ensure_unicode(PyObject *obj)
809{
810 if (!PyUnicode_Check(obj)) {
811 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +0200812 "must be str, not %.100s",
813 Py_TYPE(obj)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +0300814 return -1;
815 }
816 return PyUnicode_READY(obj);
817}
818
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200819/* Compilation of templated routines */
820
821#include "stringlib/asciilib.h"
822#include "stringlib/fastsearch.h"
823#include "stringlib/partition.h"
824#include "stringlib/split.h"
825#include "stringlib/count.h"
826#include "stringlib/find.h"
827#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200828#include "stringlib/undef.h"
829
830#include "stringlib/ucs1lib.h"
831#include "stringlib/fastsearch.h"
832#include "stringlib/partition.h"
833#include "stringlib/split.h"
834#include "stringlib/count.h"
835#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300836#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200837#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200838#include "stringlib/undef.h"
839
840#include "stringlib/ucs2lib.h"
841#include "stringlib/fastsearch.h"
842#include "stringlib/partition.h"
843#include "stringlib/split.h"
844#include "stringlib/count.h"
845#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300846#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200847#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200848#include "stringlib/undef.h"
849
850#include "stringlib/ucs4lib.h"
851#include "stringlib/fastsearch.h"
852#include "stringlib/partition.h"
853#include "stringlib/split.h"
854#include "stringlib/count.h"
855#include "stringlib/find.h"
Serhiy Storchakae2cef882013-04-13 22:45:04 +0300856#include "stringlib/replace.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200857#include "stringlib/find_max_char.h"
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200858#include "stringlib/undef.h"
859
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200860#include "stringlib/unicodedefs.h"
861#include "stringlib/fastsearch.h"
862#include "stringlib/count.h"
863#include "stringlib/find.h"
Antoine Pitrou0a3229d2011-11-21 20:39:13 +0100864#include "stringlib/undef.h"
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200865
Guido van Rossumd57fd912000-03-10 22:53:23 +0000866/* --- Unicode Object ----------------------------------------------------- */
867
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -0700868static inline Py_ssize_t
869findchar(const void *s, int kind,
870 Py_ssize_t size, Py_UCS4 ch,
871 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200872{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200873 switch (kind) {
874 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200875 if ((Py_UCS1) ch != ch)
876 return -1;
877 if (direction > 0)
878 return ucs1lib_find_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
879 else
880 return ucs1lib_rfind_char((Py_UCS1 *) s, size, (Py_UCS1) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200881 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200882 if ((Py_UCS2) ch != ch)
883 return -1;
884 if (direction > 0)
885 return ucs2lib_find_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
886 else
887 return ucs2lib_rfind_char((Py_UCS2 *) s, size, (Py_UCS2) ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200888 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka413fdce2015-11-14 15:42:17 +0200889 if (direction > 0)
890 return ucs4lib_find_char((Py_UCS4 *) s, size, ch);
891 else
892 return ucs4lib_rfind_char((Py_UCS4 *) s, size, ch);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200893 default:
Barry Warsawb2e57942017-09-14 18:13:16 -0700894 Py_UNREACHABLE();
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200895 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896}
897
Victor Stinnerafffce42012-10-03 23:03:17 +0200898#ifdef Py_DEBUG
Martin Panter6245cb32016-04-15 02:14:19 +0000899/* Fill the data of a Unicode string with invalid characters to detect bugs
Victor Stinnerafffce42012-10-03 23:03:17 +0200900 earlier.
901
902 _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
903 ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
904 invalid character in Unicode 6.0. */
905static void
906unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
907{
908 int kind = PyUnicode_KIND(unicode);
909 Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
910 Py_ssize_t length = _PyUnicode_LENGTH(unicode);
911 if (length <= old_length)
912 return;
913 memset(data + old_length * kind, 0xff, (length - old_length) * kind);
914}
915#endif
916
Victor Stinnerfe226c02011-10-03 03:52:20 +0200917static PyObject*
918resize_compact(PyObject *unicode, Py_ssize_t length)
919{
920 Py_ssize_t char_size;
921 Py_ssize_t struct_size;
922 Py_ssize_t new_size;
923 int share_wstr;
Victor Stinner84def372011-12-11 20:04:56 +0100924 PyObject *new_unicode;
Victor Stinnerafffce42012-10-03 23:03:17 +0200925#ifdef Py_DEBUG
926 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
927#endif
928
Victor Stinner79891572012-05-03 13:43:07 +0200929 assert(unicode_modifiable(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200930 assert(PyUnicode_IS_READY(unicode));
Victor Stinner488fa492011-12-12 00:01:39 +0100931 assert(PyUnicode_IS_COMPACT(unicode));
932
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200933 char_size = PyUnicode_KIND(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100934 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerfe226c02011-10-03 03:52:20 +0200935 struct_size = sizeof(PyASCIIObject);
936 else
937 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200938 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200939
Victor Stinnerfe226c02011-10-03 03:52:20 +0200940 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
941 PyErr_NoMemory();
942 return NULL;
943 }
944 new_size = (struct_size + (length + 1) * char_size);
945
Serhiy Storchaka7aa69082015-12-03 01:02:03 +0200946 if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
947 PyObject_DEL(_PyUnicode_UTF8(unicode));
948 _PyUnicode_UTF8(unicode) = NULL;
949 _PyUnicode_UTF8_LENGTH(unicode) = 0;
950 }
Victor Stinner84def372011-12-11 20:04:56 +0100951 _Py_DEC_REFTOTAL;
952 _Py_ForgetReference(unicode);
953
Serhiy Storchaka20b39b22014-09-28 11:27:24 +0300954 new_unicode = (PyObject *)PyObject_REALLOC(unicode, new_size);
Victor Stinner84def372011-12-11 20:04:56 +0100955 if (new_unicode == NULL) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +0100956 _Py_NewReference(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200957 PyErr_NoMemory();
958 return NULL;
959 }
Victor Stinner84def372011-12-11 20:04:56 +0100960 unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200961 _Py_NewReference(unicode);
Victor Stinner84def372011-12-11 20:04:56 +0100962
Victor Stinnerfe226c02011-10-03 03:52:20 +0200963 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200964 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200965 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinner488fa492011-12-12 00:01:39 +0100966 if (!PyUnicode_IS_ASCII(unicode))
Victor Stinnerc379ead2011-10-03 12:52:27 +0200967 _PyUnicode_WSTR_LENGTH(unicode) = length;
968 }
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100969 else if (_PyUnicode_HAS_WSTR_MEMORY(unicode)) {
970 PyObject_DEL(_PyUnicode_WSTR(unicode));
971 _PyUnicode_WSTR(unicode) = NULL;
Victor Stinner5bc03a62016-01-27 16:56:53 +0100972 if (!PyUnicode_IS_ASCII(unicode))
973 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Victor Stinnerbbbac2e2013-02-07 23:12:46 +0100974 }
Victor Stinnerafffce42012-10-03 23:03:17 +0200975#ifdef Py_DEBUG
976 unicode_fill_invalid(unicode, old_length);
977#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200978 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
979 length, 0);
Victor Stinner79891572012-05-03 13:43:07 +0200980 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200981 return unicode;
982}
983
Alexander Belopolsky40018472011-02-26 01:02:56 +0000984static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200985resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000986{
Victor Stinner95663112011-10-04 01:03:50 +0200987 wchar_t *wstr;
Victor Stinner7a9105a2011-12-12 00:13:42 +0100988 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200990 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000991
Victor Stinnerfe226c02011-10-03 03:52:20 +0200992 if (PyUnicode_IS_READY(unicode)) {
993 Py_ssize_t char_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200994 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200995 void *data;
Victor Stinnerafffce42012-10-03 23:03:17 +0200996#ifdef Py_DEBUG
997 Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
998#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200999
1000 data = _PyUnicode_DATA_ANY(unicode);
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001001 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +02001002 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
1003 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001004
1005 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
1006 PyErr_NoMemory();
1007 return -1;
1008 }
1009 new_size = (length + 1) * char_size;
1010
Victor Stinner7a9105a2011-12-12 00:13:42 +01001011 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
1012 {
1013 PyObject_DEL(_PyUnicode_UTF8(unicode));
1014 _PyUnicode_UTF8(unicode) = NULL;
1015 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1016 }
1017
Victor Stinnerfe226c02011-10-03 03:52:20 +02001018 data = (PyObject *)PyObject_REALLOC(data, new_size);
1019 if (data == NULL) {
1020 PyErr_NoMemory();
1021 return -1;
1022 }
1023 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001024 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001025 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001026 _PyUnicode_WSTR_LENGTH(unicode) = length;
1027 }
1028 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +02001029 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +02001030 _PyUnicode_UTF8_LENGTH(unicode) = length;
1031 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001032 _PyUnicode_LENGTH(unicode) = length;
1033 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinnerafffce42012-10-03 23:03:17 +02001034#ifdef Py_DEBUG
1035 unicode_fill_invalid(unicode, old_length);
1036#endif
Victor Stinner95663112011-10-04 01:03:50 +02001037 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001038 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001039 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001040 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02001041 }
Victor Stinner95663112011-10-04 01:03:50 +02001042 assert(_PyUnicode_WSTR(unicode) != NULL);
1043
1044 /* check for integer overflow */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001045 if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
Victor Stinner95663112011-10-04 01:03:50 +02001046 PyErr_NoMemory();
1047 return -1;
1048 }
Victor Stinner7a9105a2011-12-12 00:13:42 +01001049 new_size = sizeof(wchar_t) * (length + 1);
Victor Stinner95663112011-10-04 01:03:50 +02001050 wstr = _PyUnicode_WSTR(unicode);
Victor Stinner7a9105a2011-12-12 00:13:42 +01001051 wstr = PyObject_REALLOC(wstr, new_size);
Victor Stinner95663112011-10-04 01:03:50 +02001052 if (!wstr) {
1053 PyErr_NoMemory();
1054 return -1;
1055 }
1056 _PyUnicode_WSTR(unicode) = wstr;
1057 _PyUnicode_WSTR(unicode)[length] = 0;
1058 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001059 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001060 return 0;
1061}
1062
Victor Stinnerfe226c02011-10-03 03:52:20 +02001063static PyObject*
1064resize_copy(PyObject *unicode, Py_ssize_t length)
1065{
1066 Py_ssize_t copy_length;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001067 if (_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001068 PyObject *copy;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001069
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03001070 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001071
1072 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
1073 if (copy == NULL)
1074 return NULL;
1075
1076 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerd3f08822012-05-29 12:57:52 +02001077 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001078 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +02001079 }
1080 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001081 PyObject *w;
Victor Stinner7a9105a2011-12-12 00:13:42 +01001082
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001083 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +02001084 if (w == NULL)
1085 return NULL;
1086 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
1087 copy_length = Py_MIN(copy_length, length);
Christian Heimesf051e432016-09-13 20:22:02 +02001088 memcpy(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
Victor Stinnerc6cf1ba2012-10-23 02:54:47 +02001089 copy_length * sizeof(wchar_t));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001090 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001091 }
1092}
1093
Guido van Rossumd57fd912000-03-10 22:53:23 +00001094/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +00001095 Ux0000 terminated; some code (e.g. new_identifier)
1096 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001097
1098 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +00001099 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +00001100
1101*/
1102
Alexander Belopolsky40018472011-02-26 01:02:56 +00001103static PyUnicodeObject *
1104_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001105{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001106 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001107 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001108
Thomas Wouters477c8d52006-05-27 19:21:47 +00001109 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +00001110 if (length == 0 && unicode_empty != NULL) {
1111 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001112 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001113 }
1114
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001115 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -07001116 if (length > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00001117 return (PyUnicodeObject *)PyErr_NoMemory();
1118 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001119 if (length < 0) {
1120 PyErr_SetString(PyExc_SystemError,
1121 "Negative size passed to _PyUnicode_New");
1122 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001123 }
1124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001125 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
1126 if (unicode == NULL)
1127 return NULL;
1128 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
Victor Stinner68b674c2013-10-29 19:31:43 +01001129
1130 _PyUnicode_WSTR_LENGTH(unicode) = length;
1131 _PyUnicode_HASH(unicode) = -1;
1132 _PyUnicode_STATE(unicode).interned = 0;
1133 _PyUnicode_STATE(unicode).kind = 0;
1134 _PyUnicode_STATE(unicode).compact = 0;
1135 _PyUnicode_STATE(unicode).ready = 0;
1136 _PyUnicode_STATE(unicode).ascii = 0;
1137 _PyUnicode_DATA_ANY(unicode) = NULL;
1138 _PyUnicode_LENGTH(unicode) = 0;
1139 _PyUnicode_UTF8(unicode) = NULL;
1140 _PyUnicode_UTF8_LENGTH(unicode) = 0;
1141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001142 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
1143 if (!_PyUnicode_WSTR(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001144 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00001145 PyErr_NoMemory();
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001146 return NULL;
Guido van Rossum3c1bb802000-04-27 20:13:50 +00001147 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001148
Jeremy Hyltond8082792003-09-16 19:41:39 +00001149 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +00001150 * the caller fails before initializing str -- unicode_resize()
1151 * reads str[0], and the Keep-Alive optimization can keep memory
1152 * allocated for str alive across a call to unicode_dealloc(unicode).
1153 * We don't want unicode_resize to read uninitialized memory in
1154 * that case.
1155 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001156 _PyUnicode_WSTR(unicode)[0] = 0;
1157 _PyUnicode_WSTR(unicode)[length] = 0;
Victor Stinner68b674c2013-10-29 19:31:43 +01001158
Victor Stinner7931d9a2011-11-04 00:22:48 +01001159 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001160 return unicode;
1161}
1162
Victor Stinnerf42dc442011-10-02 23:33:16 +02001163static const char*
1164unicode_kind_name(PyObject *unicode)
1165{
Victor Stinner42dfd712011-10-03 14:41:45 +02001166 /* don't check consistency: unicode_kind_name() is called from
1167 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +02001168 if (!PyUnicode_IS_COMPACT(unicode))
1169 {
1170 if (!PyUnicode_IS_READY(unicode))
1171 return "wstr";
Benjamin Petersonead6b532011-12-20 17:23:42 -06001172 switch (PyUnicode_KIND(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001173 {
1174 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001175 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001176 return "legacy ascii";
1177 else
1178 return "legacy latin1";
1179 case PyUnicode_2BYTE_KIND:
1180 return "legacy UCS2";
1181 case PyUnicode_4BYTE_KIND:
1182 return "legacy UCS4";
1183 default:
1184 return "<legacy invalid kind>";
1185 }
1186 }
1187 assert(PyUnicode_IS_READY(unicode));
Benjamin Petersonead6b532011-12-20 17:23:42 -06001188 switch (PyUnicode_KIND(unicode)) {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001189 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001190 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001191 return "ascii";
1192 else
Victor Stinnera3b334d2011-10-03 13:53:37 +02001193 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001194 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001195 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001196 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +02001197 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +02001198 default:
1199 return "<invalid compact kind>";
1200 }
1201}
1202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001203#ifdef Py_DEBUG
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001204/* Functions wrapping macros for use in debugger */
Victor Stinnera42de742018-11-22 10:25:22 +01001205char *_PyUnicode_utf8(void *unicode_raw){
1206 PyObject *unicode = _PyObject_CAST(unicode_raw);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001207 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001208}
1209
Victor Stinnera42de742018-11-22 10:25:22 +01001210void *_PyUnicode_compact_data(void *unicode_raw) {
1211 PyObject *unicode = _PyObject_CAST(unicode_raw);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001212 return _PyUnicode_COMPACT_DATA(unicode);
1213}
Victor Stinnera42de742018-11-22 10:25:22 +01001214void *_PyUnicode_data(void *unicode_raw) {
1215 PyObject *unicode = _PyObject_CAST(unicode_raw);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216 printf("obj %p\n", unicode);
1217 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
1218 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
1219 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
1220 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
1221 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
1222 return PyUnicode_DATA(unicode);
1223}
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001224
1225void
1226_PyUnicode_Dump(PyObject *op)
1227{
1228 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +02001229 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
1230 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
1231 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +02001232
Victor Stinnera849a4b2011-10-03 12:12:11 +02001233 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +02001234 {
1235 if (ascii->state.ascii)
1236 data = (ascii + 1);
1237 else
1238 data = (compact + 1);
1239 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001240 else
1241 data = unicode->data.any;
Victor Stinner293f3f52014-07-01 08:57:10 +02001242 printf("%s: len=%" PY_FORMAT_SIZE_T "u, ",
1243 unicode_kind_name(op), ascii->length);
Victor Stinner0d60e872011-10-23 19:47:19 +02001244
Victor Stinnera849a4b2011-10-03 12:12:11 +02001245 if (ascii->wstr == data)
1246 printf("shared ");
1247 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +02001248
Victor Stinnera3b334d2011-10-03 13:53:37 +02001249 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinner293f3f52014-07-01 08:57:10 +02001250 printf(" (%" PY_FORMAT_SIZE_T "u), ", compact->wstr_length);
Victor Stinnera849a4b2011-10-03 12:12:11 +02001251 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
1252 printf("shared ");
Victor Stinner293f3f52014-07-01 08:57:10 +02001253 printf("utf8=%p (%" PY_FORMAT_SIZE_T "u)",
1254 compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001255 }
Victor Stinnera849a4b2011-10-03 12:12:11 +02001256 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +02001257}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258#endif
1259
1260PyObject *
1261PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
1262{
1263 PyObject *obj;
1264 PyCompactUnicodeObject *unicode;
1265 void *data;
Victor Stinner8f825062012-04-27 13:55:39 +02001266 enum PyUnicode_Kind kind;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001267 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001268 Py_ssize_t char_size;
1269 Py_ssize_t struct_size;
1270
1271 /* Optimization for empty strings */
1272 if (size == 0 && unicode_empty != NULL) {
1273 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001274 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001275 }
1276
Victor Stinner9e9d6892011-10-04 01:02:02 +02001277 is_ascii = 0;
1278 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001279 struct_size = sizeof(PyCompactUnicodeObject);
1280 if (maxchar < 128) {
Victor Stinner8f825062012-04-27 13:55:39 +02001281 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001282 char_size = 1;
1283 is_ascii = 1;
1284 struct_size = sizeof(PyASCIIObject);
1285 }
1286 else if (maxchar < 256) {
Victor Stinner8f825062012-04-27 13:55:39 +02001287 kind = PyUnicode_1BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001288 char_size = 1;
1289 }
1290 else if (maxchar < 65536) {
Victor Stinner8f825062012-04-27 13:55:39 +02001291 kind = PyUnicode_2BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001292 char_size = 2;
1293 if (sizeof(wchar_t) == 2)
1294 is_sharing = 1;
1295 }
1296 else {
Victor Stinnerc9590ad2012-03-04 01:34:37 +01001297 if (maxchar > MAX_UNICODE) {
1298 PyErr_SetString(PyExc_SystemError,
1299 "invalid maximum character passed to PyUnicode_New");
1300 return NULL;
1301 }
Victor Stinner8f825062012-04-27 13:55:39 +02001302 kind = PyUnicode_4BYTE_KIND;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001303 char_size = 4;
1304 if (sizeof(wchar_t) == 4)
1305 is_sharing = 1;
1306 }
1307
1308 /* Ensure we won't overflow the size. */
1309 if (size < 0) {
1310 PyErr_SetString(PyExc_SystemError,
1311 "Negative size passed to PyUnicode_New");
1312 return NULL;
1313 }
1314 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
1315 return PyErr_NoMemory();
1316
1317 /* Duplicated allocation code from _PyObject_New() instead of a call to
1318 * PyObject_New() so we are able to allocate space for the object and
1319 * it's data buffer.
1320 */
1321 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
1322 if (obj == NULL)
1323 return PyErr_NoMemory();
1324 obj = PyObject_INIT(obj, &PyUnicode_Type);
1325 if (obj == NULL)
1326 return NULL;
1327
1328 unicode = (PyCompactUnicodeObject *)obj;
1329 if (is_ascii)
1330 data = ((PyASCIIObject*)obj) + 1;
1331 else
1332 data = unicode + 1;
1333 _PyUnicode_LENGTH(unicode) = size;
1334 _PyUnicode_HASH(unicode) = -1;
1335 _PyUnicode_STATE(unicode).interned = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001336 _PyUnicode_STATE(unicode).kind = kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337 _PyUnicode_STATE(unicode).compact = 1;
1338 _PyUnicode_STATE(unicode).ready = 1;
1339 _PyUnicode_STATE(unicode).ascii = is_ascii;
1340 if (is_ascii) {
1341 ((char*)data)[size] = 0;
1342 _PyUnicode_WSTR(unicode) = NULL;
1343 }
Victor Stinner8f825062012-04-27 13:55:39 +02001344 else if (kind == PyUnicode_1BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001345 ((char*)data)[size] = 0;
1346 _PyUnicode_WSTR(unicode) = NULL;
1347 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001348 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001349 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001350 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001351 else {
1352 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +02001353 unicode->utf8_length = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001354 if (kind == PyUnicode_2BYTE_KIND)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001355 ((Py_UCS2*)data)[size] = 0;
Victor Stinner8f825062012-04-27 13:55:39 +02001356 else /* kind == PyUnicode_4BYTE_KIND */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001357 ((Py_UCS4*)data)[size] = 0;
1358 if (is_sharing) {
1359 _PyUnicode_WSTR_LENGTH(unicode) = size;
1360 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
1361 }
1362 else {
1363 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1364 _PyUnicode_WSTR(unicode) = NULL;
1365 }
1366 }
Victor Stinner8f825062012-04-27 13:55:39 +02001367#ifdef Py_DEBUG
Victor Stinnerafffce42012-10-03 23:03:17 +02001368 unicode_fill_invalid((PyObject*)unicode, 0);
Victor Stinner8f825062012-04-27 13:55:39 +02001369#endif
Victor Stinner7931d9a2011-11-04 00:22:48 +01001370 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001371 return obj;
1372}
1373
1374#if SIZEOF_WCHAR_T == 2
1375/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
1376 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +02001377 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001378
1379 This function assumes that unicode can hold one more code point than wstr
1380 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001381static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001382unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001383 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001384{
1385 const wchar_t *iter;
1386 Py_UCS4 *ucs4_out;
1387
Victor Stinner910337b2011-10-03 03:20:16 +02001388 assert(unicode != NULL);
1389 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1391 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1392
1393 for (iter = begin; iter < end; ) {
1394 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1395 _PyUnicode_GET_LENGTH(unicode)));
Victor Stinner551ac952011-11-29 22:58:13 +01001396 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1397 && (iter+1) < end
1398 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 {
Victor Stinner551ac952011-11-29 22:58:13 +01001400 *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401 iter += 2;
1402 }
1403 else {
1404 *ucs4_out++ = *iter;
1405 iter++;
1406 }
1407 }
1408 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1409 _PyUnicode_GET_LENGTH(unicode)));
1410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001411}
1412#endif
1413
Victor Stinnercd9950f2011-10-02 00:34:53 +02001414static int
Victor Stinner488fa492011-12-12 00:01:39 +01001415unicode_check_modifiable(PyObject *unicode)
Victor Stinnercd9950f2011-10-02 00:34:53 +02001416{
Victor Stinner488fa492011-12-12 00:01:39 +01001417 if (!unicode_modifiable(unicode)) {
Victor Stinner01698042011-10-04 00:04:26 +02001418 PyErr_SetString(PyExc_SystemError,
Victor Stinner488fa492011-12-12 00:01:39 +01001419 "Cannot modify a string currently used");
Victor Stinnercd9950f2011-10-02 00:34:53 +02001420 return -1;
1421 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02001422 return 0;
1423}
1424
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001425static int
1426_copy_characters(PyObject *to, Py_ssize_t to_start,
1427 PyObject *from, Py_ssize_t from_start,
1428 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001429{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001430 unsigned int from_kind, to_kind;
1431 void *from_data, *to_data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001432
Victor Stinneree4544c2012-05-09 22:24:08 +02001433 assert(0 <= how_many);
1434 assert(0 <= from_start);
1435 assert(0 <= to_start);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001436 assert(PyUnicode_Check(from));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001437 assert(PyUnicode_IS_READY(from));
Victor Stinneree4544c2012-05-09 22:24:08 +02001438 assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001439
Victor Stinnerd3f08822012-05-29 12:57:52 +02001440 assert(PyUnicode_Check(to));
1441 assert(PyUnicode_IS_READY(to));
1442 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1443
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001444 if (how_many == 0)
1445 return 0;
1446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001447 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001448 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001449 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001450 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001451
Victor Stinnerf1852262012-06-16 16:38:26 +02001452#ifdef Py_DEBUG
1453 if (!check_maxchar
1454 && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
1455 {
1456 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1457 Py_UCS4 ch;
1458 Py_ssize_t i;
1459 for (i=0; i < how_many; i++) {
1460 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1461 assert(ch <= to_maxchar);
1462 }
1463 }
1464#endif
1465
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001466 if (from_kind == to_kind) {
Victor Stinnerf1852262012-06-16 16:38:26 +02001467 if (check_maxchar
1468 && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
1469 {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001470 /* Writing Latin-1 characters into an ASCII string requires to
1471 check that all written characters are pure ASCII */
Victor Stinnerf1852262012-06-16 16:38:26 +02001472 Py_UCS4 max_char;
1473 max_char = ucs1lib_find_max_char(from_data,
1474 (Py_UCS1*)from_data + how_many);
1475 if (max_char >= 128)
1476 return -1;
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001477 }
Christian Heimesf051e432016-09-13 20:22:02 +02001478 memcpy((char*)to_data + to_kind * to_start,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001479 (char*)from_data + from_kind * from_start,
1480 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001481 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001482 else if (from_kind == PyUnicode_1BYTE_KIND
1483 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001484 {
1485 _PyUnicode_CONVERT_BYTES(
1486 Py_UCS1, Py_UCS2,
1487 PyUnicode_1BYTE_DATA(from) + from_start,
1488 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1489 PyUnicode_2BYTE_DATA(to) + to_start
1490 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001491 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001492 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001493 && to_kind == PyUnicode_4BYTE_KIND)
1494 {
1495 _PyUnicode_CONVERT_BYTES(
1496 Py_UCS1, Py_UCS4,
1497 PyUnicode_1BYTE_DATA(from) + from_start,
1498 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1499 PyUnicode_4BYTE_DATA(to) + to_start
1500 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001501 }
1502 else if (from_kind == PyUnicode_2BYTE_KIND
1503 && to_kind == PyUnicode_4BYTE_KIND)
1504 {
1505 _PyUnicode_CONVERT_BYTES(
1506 Py_UCS2, Py_UCS4,
1507 PyUnicode_2BYTE_DATA(from) + from_start,
1508 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1509 PyUnicode_4BYTE_DATA(to) + to_start
1510 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001511 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001512 else {
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001513 assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
1514
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001515 if (!check_maxchar) {
1516 if (from_kind == PyUnicode_2BYTE_KIND
1517 && to_kind == PyUnicode_1BYTE_KIND)
1518 {
1519 _PyUnicode_CONVERT_BYTES(
1520 Py_UCS2, Py_UCS1,
1521 PyUnicode_2BYTE_DATA(from) + from_start,
1522 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1523 PyUnicode_1BYTE_DATA(to) + to_start
1524 );
1525 }
1526 else if (from_kind == PyUnicode_4BYTE_KIND
1527 && to_kind == PyUnicode_1BYTE_KIND)
1528 {
1529 _PyUnicode_CONVERT_BYTES(
1530 Py_UCS4, Py_UCS1,
1531 PyUnicode_4BYTE_DATA(from) + from_start,
1532 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1533 PyUnicode_1BYTE_DATA(to) + to_start
1534 );
1535 }
1536 else if (from_kind == PyUnicode_4BYTE_KIND
1537 && to_kind == PyUnicode_2BYTE_KIND)
1538 {
1539 _PyUnicode_CONVERT_BYTES(
1540 Py_UCS4, Py_UCS2,
1541 PyUnicode_4BYTE_DATA(from) + from_start,
1542 PyUnicode_4BYTE_DATA(from) + from_start + how_many,
1543 PyUnicode_2BYTE_DATA(to) + to_start
1544 );
1545 }
1546 else {
Barry Warsawb2e57942017-09-14 18:13:16 -07001547 Py_UNREACHABLE();
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001548 }
1549 }
Victor Stinnerf1852262012-06-16 16:38:26 +02001550 else {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001551 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001552 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001553 Py_ssize_t i;
1554
Victor Stinnera0702ab2011-09-29 14:14:38 +02001555 for (i=0; i < how_many; i++) {
1556 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinnerc9d369f2012-06-16 02:22:37 +02001557 if (ch > to_maxchar)
1558 return -1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001559 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1560 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001561 }
1562 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001563 return 0;
1564}
1565
Victor Stinnerd3f08822012-05-29 12:57:52 +02001566void
1567_PyUnicode_FastCopyCharacters(
1568 PyObject *to, Py_ssize_t to_start,
1569 PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001570{
1571 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1572}
1573
1574Py_ssize_t
1575PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1576 PyObject *from, Py_ssize_t from_start,
1577 Py_ssize_t how_many)
1578{
1579 int err;
1580
1581 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1582 PyErr_BadInternalCall();
1583 return -1;
1584 }
1585
Benjamin Petersonbac79492012-01-14 13:34:47 -05001586 if (PyUnicode_READY(from) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001587 return -1;
Benjamin Petersonbac79492012-01-14 13:34:47 -05001588 if (PyUnicode_READY(to) == -1)
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001589 return -1;
1590
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001591 if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001592 PyErr_SetString(PyExc_IndexError, "string index out of range");
1593 return -1;
1594 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001595 if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
Victor Stinnerd3f08822012-05-29 12:57:52 +02001596 PyErr_SetString(PyExc_IndexError, "string index out of range");
1597 return -1;
1598 }
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03001599 if (how_many < 0) {
1600 PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
1601 return -1;
1602 }
1603 how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001604 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1605 PyErr_Format(PyExc_SystemError,
Victor Stinnera33bce02014-07-04 22:47:46 +02001606 "Cannot write %zi characters at %zi "
1607 "in a string of %zi characters",
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001608 how_many, to_start, PyUnicode_GET_LENGTH(to));
1609 return -1;
1610 }
1611
1612 if (how_many == 0)
1613 return 0;
1614
Victor Stinner488fa492011-12-12 00:01:39 +01001615 if (unicode_check_modifiable(to))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001616 return -1;
1617
1618 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1619 if (err) {
1620 PyErr_Format(PyExc_SystemError,
1621 "Cannot copy %s characters "
1622 "into a string of %s characters",
1623 unicode_kind_name(from),
1624 unicode_kind_name(to));
1625 return -1;
1626 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001627 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001628}
1629
Victor Stinner17222162011-09-28 22:15:37 +02001630/* Find the maximum code point and count the number of surrogate pairs so a
1631 correct string length can be computed before converting a string to UCS4.
1632 This function counts single surrogates as a character and not as a pair.
1633
1634 Return 0 on success, or -1 on error. */
1635static int
1636find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1637 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001638{
1639 const wchar_t *iter;
Victor Stinner8faf8212011-12-08 22:14:11 +01001640 Py_UCS4 ch;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001641
Victor Stinnerc53be962011-10-02 21:33:54 +02001642 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643 *num_surrogates = 0;
1644 *maxchar = 0;
1645
1646 for (iter = begin; iter < end; ) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001647#if SIZEOF_WCHAR_T == 2
Victor Stinnercf77da92013-03-06 01:09:24 +01001648 if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
1649 && (iter+1) < end
1650 && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
1651 {
1652 ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
1653 ++(*num_surrogates);
1654 iter += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001655 }
1656 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657#endif
Victor Stinner8faf8212011-12-08 22:14:11 +01001658 {
1659 ch = *iter;
1660 iter++;
1661 }
1662 if (ch > *maxchar) {
1663 *maxchar = ch;
1664 if (*maxchar > MAX_UNICODE) {
1665 PyErr_Format(PyExc_ValueError,
1666 "character U+%x is not in range [U+0000; U+10ffff]",
1667 ch);
1668 return -1;
1669 }
1670 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001671 }
1672 return 0;
1673}
1674
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01001675int
1676_PyUnicode_Ready(PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001677{
1678 wchar_t *end;
1679 Py_UCS4 maxchar = 0;
1680 Py_ssize_t num_surrogates;
1681#if SIZEOF_WCHAR_T == 2
1682 Py_ssize_t length_wo_surrogates;
1683#endif
1684
Georg Brandl7597add2011-10-05 16:36:47 +02001685 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001686 strings were created using _PyObject_New() and where no canonical
1687 representation (the str field) has been set yet aka strings
1688 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001689 assert(_PyUnicode_CHECK(unicode));
1690 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001691 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001692 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001693 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001694 /* Actually, it should neither be interned nor be anything else: */
1695 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001696
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001697 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001698 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001699 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001700 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001701
1702 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001703 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1704 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001705 PyErr_NoMemory();
1706 return -1;
1707 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001708 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001709 _PyUnicode_WSTR(unicode), end,
1710 PyUnicode_1BYTE_DATA(unicode));
1711 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1712 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1713 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1714 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001715 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001716 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001717 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001718 }
1719 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001720 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001721 _PyUnicode_UTF8(unicode) = NULL;
1722 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001723 }
1724 PyObject_FREE(_PyUnicode_WSTR(unicode));
1725 _PyUnicode_WSTR(unicode) = NULL;
1726 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1727 }
1728 /* In this case we might have to convert down from 4-byte native
1729 wchar_t to 2-byte unicode. */
1730 else if (maxchar < 65536) {
1731 assert(num_surrogates == 0 &&
1732 "FindMaxCharAndNumSurrogatePairs() messed up");
1733
Victor Stinner506f5922011-09-28 22:34:18 +02001734#if SIZEOF_WCHAR_T == 2
1735 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001736 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001737 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1738 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1739 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001740 _PyUnicode_UTF8(unicode) = NULL;
1741 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001742#else
1743 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001744 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001745 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001746 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001747 PyErr_NoMemory();
1748 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001749 }
Victor Stinner506f5922011-09-28 22:34:18 +02001750 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1751 _PyUnicode_WSTR(unicode), end,
1752 PyUnicode_2BYTE_DATA(unicode));
1753 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1754 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1755 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001756 _PyUnicode_UTF8(unicode) = NULL;
1757 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001758 PyObject_FREE(_PyUnicode_WSTR(unicode));
1759 _PyUnicode_WSTR(unicode) = NULL;
1760 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1761#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001762 }
1763 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1764 else {
1765#if SIZEOF_WCHAR_T == 2
1766 /* in case the native representation is 2-bytes, we need to allocate a
1767 new normalized 4-byte version. */
1768 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Serhiy Storchakae55181f2015-02-20 21:34:06 +02001769 if (length_wo_surrogates > PY_SSIZE_T_MAX / 4 - 1) {
1770 PyErr_NoMemory();
1771 return -1;
1772 }
Victor Stinnerc3c74152011-10-02 20:39:55 +02001773 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1774 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775 PyErr_NoMemory();
1776 return -1;
1777 }
1778 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1779 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001780 _PyUnicode_UTF8(unicode) = NULL;
1781 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001782 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1783 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001784 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001785 PyObject_FREE(_PyUnicode_WSTR(unicode));
1786 _PyUnicode_WSTR(unicode) = NULL;
1787 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1788#else
1789 assert(num_surrogates == 0);
1790
Victor Stinnerc3c74152011-10-02 20:39:55 +02001791 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001792 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001793 _PyUnicode_UTF8(unicode) = NULL;
1794 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001795 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1796#endif
1797 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1798 }
1799 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001800 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001801 return 0;
1802}
1803
Alexander Belopolsky40018472011-02-26 01:02:56 +00001804static void
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02001805unicode_dealloc(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001806{
Walter Dörwald16807132007-05-25 13:52:07 +00001807 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001808 case SSTATE_NOT_INTERNED:
1809 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001810
Benjamin Peterson29060642009-01-31 22:14:21 +00001811 case SSTATE_INTERNED_MORTAL:
1812 /* revive dead object temporarily for DelItem */
1813 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001814 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001815 Py_FatalError(
1816 "deletion of interned string failed");
1817 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001818
Benjamin Peterson29060642009-01-31 22:14:21 +00001819 case SSTATE_INTERNED_IMMORTAL:
1820 Py_FatalError("Immortal interned string died.");
Stefan Krahf432a322017-08-21 13:09:59 +02001821 /* fall through */
Walter Dörwald16807132007-05-25 13:52:07 +00001822
Benjamin Peterson29060642009-01-31 22:14:21 +00001823 default:
1824 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001825 }
1826
Victor Stinner03490912011-10-03 23:45:12 +02001827 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001829 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001830 PyObject_DEL(_PyUnicode_UTF8(unicode));
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001831 if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode))
1832 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001833
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001834 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001835}
1836
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001837#ifdef Py_DEBUG
1838static int
1839unicode_is_singleton(PyObject *unicode)
1840{
1841 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1842 if (unicode == unicode_empty)
1843 return 1;
1844 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1845 {
1846 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1847 if (ch < 256 && unicode_latin1[ch] == unicode)
1848 return 1;
1849 }
1850 return 0;
1851}
1852#endif
1853
Alexander Belopolsky40018472011-02-26 01:02:56 +00001854static int
Victor Stinner488fa492011-12-12 00:01:39 +01001855unicode_modifiable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001856{
Victor Stinner488fa492011-12-12 00:01:39 +01001857 assert(_PyUnicode_CHECK(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001858 if (Py_REFCNT(unicode) != 1)
1859 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001860 if (_PyUnicode_HASH(unicode) != -1)
1861 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001862 if (PyUnicode_CHECK_INTERNED(unicode))
1863 return 0;
Victor Stinner488fa492011-12-12 00:01:39 +01001864 if (!PyUnicode_CheckExact(unicode))
1865 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001866#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001867 /* singleton refcount is greater than 1 */
1868 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001869#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001870 return 1;
1871}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001872
Victor Stinnerfe226c02011-10-03 03:52:20 +02001873static int
1874unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1875{
1876 PyObject *unicode;
1877 Py_ssize_t old_length;
1878
1879 assert(p_unicode != NULL);
1880 unicode = *p_unicode;
1881
1882 assert(unicode != NULL);
1883 assert(PyUnicode_Check(unicode));
1884 assert(0 <= length);
1885
Victor Stinner910337b2011-10-03 03:20:16 +02001886 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001887 old_length = PyUnicode_WSTR_LENGTH(unicode);
1888 else
1889 old_length = PyUnicode_GET_LENGTH(unicode);
1890 if (old_length == length)
1891 return 0;
1892
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001893 if (length == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02001894 _Py_INCREF_UNICODE_EMPTY();
1895 if (!unicode_empty)
Benjamin Peterson29060642009-01-31 22:14:21 +00001896 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001897 Py_SETREF(*p_unicode, unicode_empty);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001898 return 0;
1899 }
1900
Victor Stinner488fa492011-12-12 00:01:39 +01001901 if (!unicode_modifiable(unicode)) {
Victor Stinnerfe226c02011-10-03 03:52:20 +02001902 PyObject *copy = resize_copy(unicode, length);
1903 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001904 return -1;
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001905 Py_SETREF(*p_unicode, copy);
Benjamin Peterson29060642009-01-31 22:14:21 +00001906 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001907 }
1908
Victor Stinnerfe226c02011-10-03 03:52:20 +02001909 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001910 PyObject *new_unicode = resize_compact(unicode, length);
1911 if (new_unicode == NULL)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001912 return -1;
Victor Stinnerb0a82a62011-12-12 13:08:33 +01001913 *p_unicode = new_unicode;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001914 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001915 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001916 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001917}
1918
Alexander Belopolsky40018472011-02-26 01:02:56 +00001919int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001920PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001921{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001922 PyObject *unicode;
1923 if (p_unicode == NULL) {
1924 PyErr_BadInternalCall();
1925 return -1;
1926 }
1927 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001928 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001929 {
1930 PyErr_BadInternalCall();
1931 return -1;
1932 }
1933 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001934}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001935
Serhiy Storchakad65c9492015-11-02 14:10:23 +02001936/* Copy an ASCII or latin1 char* string into a Python Unicode string.
Victor Stinnerc5166102012-02-22 13:55:02 +01001937
Victor Stinnerb429d3b2012-02-22 21:22:20 +01001938 WARNING: The function doesn't copy the terminating null character and
1939 doesn't check the maximum character (may write a latin1 character in an
1940 ASCII string). */
Victor Stinner184252a2012-06-16 02:57:41 +02001941static void
1942unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
1943 const char *str, Py_ssize_t len)
Victor Stinnerc5166102012-02-22 13:55:02 +01001944{
1945 enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
1946 void *data = PyUnicode_DATA(unicode);
Victor Stinner184252a2012-06-16 02:57:41 +02001947 const char *end = str + len;
Victor Stinnerc5166102012-02-22 13:55:02 +01001948
1949 switch (kind) {
1950 case PyUnicode_1BYTE_KIND: {
Victor Stinnerc5166102012-02-22 13:55:02 +01001951 assert(index + len <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner8c6db452012-10-06 00:40:45 +02001952#ifdef Py_DEBUG
1953 if (PyUnicode_IS_ASCII(unicode)) {
1954 Py_UCS4 maxchar = ucs1lib_find_max_char(
1955 (const Py_UCS1*)str,
1956 (const Py_UCS1*)str + len);
1957 assert(maxchar < 128);
1958 }
1959#endif
Antoine Pitrouba6bafc2012-02-22 16:41:50 +01001960 memcpy((char *) data + index, str, len);
Victor Stinner184252a2012-06-16 02:57:41 +02001961 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001962 }
1963 case PyUnicode_2BYTE_KIND: {
1964 Py_UCS2 *start = (Py_UCS2 *)data + index;
1965 Py_UCS2 *ucs2 = start;
1966 assert(index <= PyUnicode_GET_LENGTH(unicode));
1967
Victor Stinner184252a2012-06-16 02:57:41 +02001968 for (; str < end; ++ucs2, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001969 *ucs2 = (Py_UCS2)*str;
1970
1971 assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner184252a2012-06-16 02:57:41 +02001972 break;
Victor Stinnerc5166102012-02-22 13:55:02 +01001973 }
1974 default: {
1975 Py_UCS4 *start = (Py_UCS4 *)data + index;
1976 Py_UCS4 *ucs4 = start;
1977 assert(kind == PyUnicode_4BYTE_KIND);
1978 assert(index <= PyUnicode_GET_LENGTH(unicode));
1979
Victor Stinner184252a2012-06-16 02:57:41 +02001980 for (; str < end; ++ucs4, ++str)
Victor Stinnerc5166102012-02-22 13:55:02 +01001981 *ucs4 = (Py_UCS4)*str;
1982
1983 assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
Victor Stinnerc5166102012-02-22 13:55:02 +01001984 }
1985 }
1986}
1987
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988static PyObject*
1989get_latin1_char(unsigned char ch)
1990{
Victor Stinnera464fc12011-10-02 20:39:30 +02001991 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001992 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001993 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 if (!unicode)
1995 return NULL;
1996 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001997 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001998 unicode_latin1[ch] = unicode;
1999 }
2000 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02002001 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002002}
2003
Victor Stinner985a82a2014-01-03 12:53:47 +01002004static PyObject*
2005unicode_char(Py_UCS4 ch)
2006{
2007 PyObject *unicode;
2008
2009 assert(ch <= MAX_UNICODE);
2010
Victor Stinnerf3b46b42014-01-03 13:16:00 +01002011 if (ch < 256)
2012 return get_latin1_char(ch);
2013
Victor Stinner985a82a2014-01-03 12:53:47 +01002014 unicode = PyUnicode_New(1, ch);
2015 if (unicode == NULL)
2016 return NULL;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002017
2018 assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
2019 if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Victor Stinner985a82a2014-01-03 12:53:47 +01002020 PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
Serhiy Storchaka2e58f1a2016-10-09 23:44:48 +03002021 } else {
Victor Stinner985a82a2014-01-03 12:53:47 +01002022 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
2023 PyUnicode_4BYTE_DATA(unicode)[0] = ch;
2024 }
2025 assert(_PyUnicode_CheckConsistency(unicode, 1));
2026 return unicode;
2027}
2028
Alexander Belopolsky40018472011-02-26 01:02:56 +00002029PyObject *
2030PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002031{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002032 if (u == NULL)
2033 return (PyObject*)_PyUnicode_New(size);
2034
2035 if (size < 0) {
2036 PyErr_BadInternalCall();
2037 return NULL;
2038 }
2039
2040 return PyUnicode_FromWideChar(u, size);
2041}
2042
2043PyObject *
2044PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
2045{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002046 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 Py_UCS4 maxchar = 0;
2048 Py_ssize_t num_surrogates;
2049
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02002050 if (u == NULL && size != 0) {
2051 PyErr_BadInternalCall();
2052 return NULL;
2053 }
2054
2055 if (size == -1) {
2056 size = wcslen(u);
2057 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002058
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002059 /* If the Unicode data is known at construction time, we can apply
2060 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00002061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002062 /* Optimization for empty strings */
Serhiy Storchaka678db842013-01-26 12:16:36 +02002063 if (size == 0)
2064 _Py_RETURN_UNICODE_EMPTY();
Tim Petersced69f82003-09-16 20:30:58 +00002065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002066 /* Single character Unicode objects in the Latin-1 range are
2067 shared when using this constructor */
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002068 if (size == 1 && (Py_UCS4)*u < 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002069 return get_latin1_char((unsigned char)*u);
2070
2071 /* If not empty and not single character, copy the Unicode data
2072 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02002073 if (find_maxchar_surrogates(u, u + size,
2074 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002075 return NULL;
2076
Victor Stinner8faf8212011-12-08 22:14:11 +01002077 unicode = PyUnicode_New(size - num_surrogates, maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002078 if (!unicode)
2079 return NULL;
2080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002081 switch (PyUnicode_KIND(unicode)) {
2082 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002083 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002084 u, u + size, PyUnicode_1BYTE_DATA(unicode));
2085 break;
2086 case PyUnicode_2BYTE_KIND:
2087#if Py_UNICODE_SIZE == 2
Christian Heimesf051e432016-09-13 20:22:02 +02002088 memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002089#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02002090 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002091 u, u + size, PyUnicode_2BYTE_DATA(unicode));
2092#endif
2093 break;
2094 case PyUnicode_4BYTE_KIND:
2095#if SIZEOF_WCHAR_T == 2
2096 /* This is the only case which has to process surrogates, thus
2097 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02002098 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002099#else
2100 assert(num_surrogates == 0);
Christian Heimesf051e432016-09-13 20:22:02 +02002101 memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002102#endif
2103 break;
2104 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002105 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002106 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002107
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002108 return unicode_result(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002109}
2110
Alexander Belopolsky40018472011-02-26 01:02:56 +00002111PyObject *
2112PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002113{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002114 if (size < 0) {
2115 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00002116 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00002117 return NULL;
2118 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002119 if (u != NULL)
2120 return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
2121 else
2122 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00002123}
2124
Alexander Belopolsky40018472011-02-26 01:02:56 +00002125PyObject *
2126PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00002127{
2128 size_t size = strlen(u);
2129 if (size > PY_SSIZE_T_MAX) {
2130 PyErr_SetString(PyExc_OverflowError, "input too long");
2131 return NULL;
2132 }
Victor Stinnera1d12bb2011-12-11 21:53:09 +01002133 return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002134}
2135
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002136PyObject *
2137_PyUnicode_FromId(_Py_Identifier *id)
2138{
2139 if (!id->object) {
Victor Stinnerd1cd99b2012-02-07 23:05:55 +01002140 id->object = PyUnicode_DecodeUTF8Stateful(id->string,
2141 strlen(id->string),
2142 NULL, NULL);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002143 if (!id->object)
2144 return NULL;
2145 PyUnicode_InternInPlace(&id->object);
2146 assert(!id->next);
2147 id->next = static_strings;
2148 static_strings = id;
2149 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002150 return id->object;
2151}
2152
2153void
2154_PyUnicode_ClearStaticStrings()
2155{
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002156 _Py_Identifier *tmp, *s = static_strings;
2157 while (s) {
Serhiy Storchaka505ff752014-02-09 13:33:53 +02002158 Py_CLEAR(s->object);
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002159 tmp = s->next;
2160 s->next = NULL;
2161 s = tmp;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002162 }
Benjamin Peterson0c270a82013-01-09 09:52:01 -06002163 static_strings = NULL;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002164}
2165
Benjamin Peterson0df54292012-03-26 14:50:32 -04002166/* Internal function, doesn't check maximum character */
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002167
Victor Stinnerd3f08822012-05-29 12:57:52 +02002168PyObject*
2169_PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02002170{
Victor Stinnerd3f08822012-05-29 12:57:52 +02002171 const unsigned char *s = (const unsigned char *)buffer;
Victor Stinner785938e2011-12-11 20:09:03 +01002172 PyObject *unicode;
Victor Stinnere6b2d442011-12-11 21:54:30 +01002173 if (size == 1) {
Victor Stinner0617b6e2011-10-05 23:26:01 +02002174#ifdef Py_DEBUG
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002175 assert((unsigned char)s[0] < 128);
Victor Stinner0617b6e2011-10-05 23:26:01 +02002176#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002177 return get_latin1_char(s[0]);
Victor Stinnere6b2d442011-12-11 21:54:30 +01002178 }
Victor Stinner785938e2011-12-11 20:09:03 +01002179 unicode = PyUnicode_New(size, 127);
2180 if (!unicode)
Victor Stinner702c7342011-10-05 13:50:52 +02002181 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01002182 memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
2183 assert(_PyUnicode_CheckConsistency(unicode, 1));
2184 return unicode;
Victor Stinner702c7342011-10-05 13:50:52 +02002185}
2186
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002187static Py_UCS4
2188kind_maxchar_limit(unsigned int kind)
2189{
Benjamin Petersonead6b532011-12-20 17:23:42 -06002190 switch (kind) {
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002191 case PyUnicode_1BYTE_KIND:
2192 return 0x80;
2193 case PyUnicode_2BYTE_KIND:
2194 return 0x100;
2195 case PyUnicode_4BYTE_KIND:
2196 return 0x10000;
2197 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002198 Py_UNREACHABLE();
Victor Stinnerc80d6d22011-10-05 14:13:28 +02002199 }
2200}
2201
Victor Stinner702c7342011-10-05 13:50:52 +02002202static PyObject*
Victor Stinnerd21b58c2013-02-26 00:15:54 +01002203_PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00002204{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002206 unsigned char max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002207
Serhiy Storchaka678db842013-01-26 12:16:36 +02002208 if (size == 0)
2209 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002210 assert(size > 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02002211 if (size == 1)
2212 return get_latin1_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002213
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002214 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002215 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 if (!res)
2217 return NULL;
2218 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002219 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00002221}
2222
Victor Stinnere57b1c02011-09-28 22:20:48 +02002223static PyObject*
2224_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002225{
2226 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002227 Py_UCS2 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002228
Serhiy Storchaka678db842013-01-26 12:16:36 +02002229 if (size == 0)
2230 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002231 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002232 if (size == 1)
2233 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002234
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002235 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002236 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002237 if (!res)
2238 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002239 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002241 else {
2242 _PyUnicode_CONVERT_BYTES(
2243 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
2244 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002245 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 return res;
2247}
2248
Victor Stinnere57b1c02011-09-28 22:20:48 +02002249static PyObject*
2250_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002251{
2252 PyObject *res;
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002253 Py_UCS4 max_char;
Victor Stinnerb9275c12011-10-05 14:01:42 +02002254
Serhiy Storchaka678db842013-01-26 12:16:36 +02002255 if (size == 0)
2256 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002257 assert(size > 0);
Victor Stinner985a82a2014-01-03 12:53:47 +01002258 if (size == 1)
2259 return unicode_char(u[0]);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01002260
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002261 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002262 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002263 if (!res)
2264 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02002265 if (max_char < 256)
2266 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
2267 PyUnicode_1BYTE_DATA(res));
2268 else if (max_char < 0x10000)
2269 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
2270 PyUnicode_2BYTE_DATA(res));
2271 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002272 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002273 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002274 return res;
2275}
2276
2277PyObject*
2278PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
2279{
Victor Stinnercfed46e2011-11-22 01:29:14 +01002280 if (size < 0) {
2281 PyErr_SetString(PyExc_ValueError, "size must be positive");
2282 return NULL;
2283 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002284 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002285 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002286 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002287 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002288 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002289 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02002290 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02002291 default:
Victor Stinnerb9275c12011-10-05 14:01:42 +02002292 PyErr_SetString(PyExc_SystemError, "invalid kind");
2293 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002294 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002295}
2296
Victor Stinnerece58de2012-04-23 23:36:38 +02002297Py_UCS4
2298_PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
2299{
2300 enum PyUnicode_Kind kind;
2301 void *startptr, *endptr;
2302
2303 assert(PyUnicode_IS_READY(unicode));
2304 assert(0 <= start);
2305 assert(end <= PyUnicode_GET_LENGTH(unicode));
2306 assert(start <= end);
2307
2308 if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
2309 return PyUnicode_MAX_CHAR_VALUE(unicode);
2310
2311 if (start == end)
2312 return 127;
2313
Victor Stinner94d558b2012-04-27 22:26:58 +02002314 if (PyUnicode_IS_ASCII(unicode))
2315 return 127;
2316
Victor Stinnerece58de2012-04-23 23:36:38 +02002317 kind = PyUnicode_KIND(unicode);
Benjamin Petersonf3b7d862012-04-23 18:07:01 -04002318 startptr = PyUnicode_DATA(unicode);
Benjamin Petersonb9f4c9d2012-04-23 21:45:40 -04002319 endptr = (char *)startptr + end * kind;
2320 startptr = (char *)startptr + start * kind;
Benjamin Peterson2844a7a2012-04-23 18:00:25 -04002321 switch(kind) {
2322 case PyUnicode_1BYTE_KIND:
2323 return ucs1lib_find_max_char(startptr, endptr);
2324 case PyUnicode_2BYTE_KIND:
2325 return ucs2lib_find_max_char(startptr, endptr);
2326 case PyUnicode_4BYTE_KIND:
2327 return ucs4lib_find_max_char(startptr, endptr);
Victor Stinnerece58de2012-04-23 23:36:38 +02002328 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002329 Py_UNREACHABLE();
Victor Stinnerece58de2012-04-23 23:36:38 +02002330 }
2331}
2332
Victor Stinner25a4b292011-10-06 12:31:55 +02002333/* Ensure that a string uses the most efficient storage, if it is not the
2334 case: create a new string with of the right kind. Write NULL into *p_unicode
2335 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02002336static void
Victor Stinner25a4b292011-10-06 12:31:55 +02002337unicode_adjust_maxchar(PyObject **p_unicode)
2338{
2339 PyObject *unicode, *copy;
2340 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002341 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02002342 unsigned int kind;
2343
2344 assert(p_unicode != NULL);
2345 unicode = *p_unicode;
2346 assert(PyUnicode_IS_READY(unicode));
2347 if (PyUnicode_IS_ASCII(unicode))
2348 return;
2349
2350 len = PyUnicode_GET_LENGTH(unicode);
2351 kind = PyUnicode_KIND(unicode);
2352 if (kind == PyUnicode_1BYTE_KIND) {
2353 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002354 max_char = ucs1lib_find_max_char(u, u + len);
2355 if (max_char >= 128)
2356 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002357 }
2358 else if (kind == PyUnicode_2BYTE_KIND) {
2359 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002360 max_char = ucs2lib_find_max_char(u, u + len);
2361 if (max_char >= 256)
2362 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002363 }
2364 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002365 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02002366 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02002367 max_char = ucs4lib_find_max_char(u, u + len);
2368 if (max_char >= 0x10000)
2369 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02002370 }
Victor Stinner25a4b292011-10-06 12:31:55 +02002371 copy = PyUnicode_New(len, max_char);
Victor Stinnerca439ee2012-06-16 03:17:34 +02002372 if (copy != NULL)
2373 _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
Victor Stinner25a4b292011-10-06 12:31:55 +02002374 Py_DECREF(unicode);
2375 *p_unicode = copy;
2376}
2377
Victor Stinner034f6cf2011-09-30 02:26:44 +02002378PyObject*
Victor Stinnerbf6e5602011-12-12 01:53:47 +01002379_PyUnicode_Copy(PyObject *unicode)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002380{
Victor Stinner87af4f22011-11-21 23:03:47 +01002381 Py_ssize_t length;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002382 PyObject *copy;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002383
Victor Stinner034f6cf2011-09-30 02:26:44 +02002384 if (!PyUnicode_Check(unicode)) {
2385 PyErr_BadInternalCall();
2386 return NULL;
2387 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05002388 if (PyUnicode_READY(unicode) == -1)
Victor Stinner034f6cf2011-09-30 02:26:44 +02002389 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002390
Victor Stinner87af4f22011-11-21 23:03:47 +01002391 length = PyUnicode_GET_LENGTH(unicode);
2392 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002393 if (!copy)
2394 return NULL;
2395 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
2396
Christian Heimesf051e432016-09-13 20:22:02 +02002397 memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
Victor Stinner87af4f22011-11-21 23:03:47 +01002398 length * PyUnicode_KIND(unicode));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002399 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02002400 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02002401}
2402
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403
Victor Stinnerbc603d12011-10-02 01:00:40 +02002404/* Widen Unicode objects to larger buffers. Don't write terminating null
2405 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002406
2407void*
2408_PyUnicode_AsKind(PyObject *s, unsigned int kind)
2409{
Victor Stinnerbc603d12011-10-02 01:00:40 +02002410 Py_ssize_t len;
2411 void *result;
2412 unsigned int skind;
2413
Benjamin Petersonbac79492012-01-14 13:34:47 -05002414 if (PyUnicode_READY(s) == -1)
Victor Stinnerbc603d12011-10-02 01:00:40 +02002415 return NULL;
2416
2417 len = PyUnicode_GET_LENGTH(s);
2418 skind = PyUnicode_KIND(s);
2419 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02002420 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002421 return NULL;
2422 }
Benjamin Petersonead6b532011-12-20 17:23:42 -06002423 switch (kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02002424 case PyUnicode_2BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002425 result = PyMem_New(Py_UCS2, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002426 if (!result)
2427 return PyErr_NoMemory();
2428 assert(skind == PyUnicode_1BYTE_KIND);
2429 _PyUnicode_CONVERT_BYTES(
2430 Py_UCS1, Py_UCS2,
2431 PyUnicode_1BYTE_DATA(s),
2432 PyUnicode_1BYTE_DATA(s) + len,
2433 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002434 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002435 case PyUnicode_4BYTE_KIND:
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002436 result = PyMem_New(Py_UCS4, len);
Victor Stinnerbc603d12011-10-02 01:00:40 +02002437 if (!result)
2438 return PyErr_NoMemory();
2439 if (skind == PyUnicode_2BYTE_KIND) {
2440 _PyUnicode_CONVERT_BYTES(
2441 Py_UCS2, Py_UCS4,
2442 PyUnicode_2BYTE_DATA(s),
2443 PyUnicode_2BYTE_DATA(s) + len,
2444 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002445 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02002446 else {
2447 assert(skind == PyUnicode_1BYTE_KIND);
2448 _PyUnicode_CONVERT_BYTES(
2449 Py_UCS1, Py_UCS4,
2450 PyUnicode_1BYTE_DATA(s),
2451 PyUnicode_1BYTE_DATA(s) + len,
2452 result);
2453 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002454 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02002455 default:
2456 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 }
Victor Stinner01698042011-10-04 00:04:26 +02002458 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 return NULL;
2460}
2461
2462static Py_UCS4*
2463as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2464 int copy_null)
2465{
2466 int kind;
2467 void *data;
2468 Py_ssize_t len, targetlen;
2469 if (PyUnicode_READY(string) == -1)
2470 return NULL;
2471 kind = PyUnicode_KIND(string);
2472 data = PyUnicode_DATA(string);
2473 len = PyUnicode_GET_LENGTH(string);
2474 targetlen = len;
2475 if (copy_null)
2476 targetlen++;
2477 if (!target) {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02002478 target = PyMem_New(Py_UCS4, targetlen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002479 if (!target) {
2480 PyErr_NoMemory();
2481 return NULL;
2482 }
2483 }
2484 else {
2485 if (targetsize < targetlen) {
2486 PyErr_Format(PyExc_SystemError,
2487 "string is longer than the buffer");
2488 if (copy_null && 0 < targetsize)
2489 target[0] = 0;
2490 return NULL;
2491 }
2492 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002493 if (kind == PyUnicode_1BYTE_KIND) {
2494 Py_UCS1 *start = (Py_UCS1 *) data;
2495 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002496 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002497 else if (kind == PyUnicode_2BYTE_KIND) {
2498 Py_UCS2 *start = (Py_UCS2 *) data;
2499 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2500 }
2501 else {
2502 assert(kind == PyUnicode_4BYTE_KIND);
Christian Heimesf051e432016-09-13 20:22:02 +02002503 memcpy(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002504 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002505 if (copy_null)
2506 target[len] = 0;
2507 return target;
2508}
2509
2510Py_UCS4*
2511PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2512 int copy_null)
2513{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002514 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 PyErr_BadInternalCall();
2516 return NULL;
2517 }
2518 return as_ucs4(string, target, targetsize, copy_null);
2519}
2520
2521Py_UCS4*
2522PyUnicode_AsUCS4Copy(PyObject *string)
2523{
2524 return as_ucs4(string, NULL, 0, 1);
2525}
2526
Victor Stinner15a11362012-10-06 23:48:20 +02002527/* maximum number of characters required for output of %lld or %p.
Victor Stinnere215d962012-10-06 23:03:36 +02002528 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2529 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2530#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
Victor Stinner96865452011-03-01 23:44:09 +00002531
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002532static int
2533unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
2534 Py_ssize_t width, Py_ssize_t precision)
2535{
2536 Py_ssize_t length, fill, arglen;
2537 Py_UCS4 maxchar;
2538
2539 if (PyUnicode_READY(str) == -1)
2540 return -1;
2541
2542 length = PyUnicode_GET_LENGTH(str);
2543 if ((precision == -1 || precision >= length)
2544 && width <= length)
2545 return _PyUnicodeWriter_WriteStr(writer, str);
2546
2547 if (precision != -1)
2548 length = Py_MIN(precision, length);
2549
2550 arglen = Py_MAX(length, width);
2551 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
2552 maxchar = _PyUnicode_FindMaxChar(str, 0, length);
2553 else
2554 maxchar = writer->maxchar;
2555
2556 if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
2557 return -1;
2558
2559 if (width > length) {
2560 fill = width - length;
2561 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
2562 return -1;
2563 writer->pos += fill;
2564 }
2565
2566 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
2567 str, 0, length);
2568 writer->pos += length;
2569 return 0;
2570}
2571
2572static int
Victor Stinner998b8062018-09-12 00:23:25 +02002573unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002574 Py_ssize_t width, Py_ssize_t precision)
2575{
2576 /* UTF-8 */
2577 Py_ssize_t length;
2578 PyObject *unicode;
2579 int res;
2580
2581 length = strlen(str);
2582 if (precision != -1)
2583 length = Py_MIN(length, precision);
2584 unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
2585 if (unicode == NULL)
2586 return -1;
2587
2588 res = unicode_fromformat_write_str(writer, unicode, width, -1);
2589 Py_DECREF(unicode);
2590 return res;
2591}
2592
Victor Stinner96865452011-03-01 23:44:09 +00002593static const char*
Victor Stinnere215d962012-10-06 23:03:36 +02002594unicode_fromformat_arg(_PyUnicodeWriter *writer,
2595 const char *f, va_list *vargs)
Victor Stinner96865452011-03-01 23:44:09 +00002596{
Victor Stinnere215d962012-10-06 23:03:36 +02002597 const char *p;
2598 Py_ssize_t len;
2599 int zeropad;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002600 Py_ssize_t width;
2601 Py_ssize_t precision;
Victor Stinnere215d962012-10-06 23:03:36 +02002602 int longflag;
2603 int longlongflag;
2604 int size_tflag;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002605 Py_ssize_t fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002606
2607 p = f;
2608 f++;
Victor Stinner4c63a972012-10-06 23:55:33 +02002609 zeropad = 0;
2610 if (*f == '0') {
2611 zeropad = 1;
2612 f++;
2613 }
Victor Stinner96865452011-03-01 23:44:09 +00002614
2615 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002616 width = -1;
2617 if (Py_ISDIGIT((unsigned)*f)) {
2618 width = *f - '0';
Victor Stinner96865452011-03-01 23:44:09 +00002619 f++;
Victor Stinnere215d962012-10-06 23:03:36 +02002620 while (Py_ISDIGIT((unsigned)*f)) {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002621 if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
Victor Stinner3921e902012-10-06 23:05:00 +02002622 PyErr_SetString(PyExc_ValueError,
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002623 "width too big");
Victor Stinner3921e902012-10-06 23:05:00 +02002624 return NULL;
2625 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002626 width = (width * 10) + (*f - '0');
Victor Stinnere215d962012-10-06 23:03:36 +02002627 f++;
2628 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002629 }
2630 precision = -1;
2631 if (*f == '.') {
2632 f++;
2633 if (Py_ISDIGIT((unsigned)*f)) {
2634 precision = (*f - '0');
2635 f++;
2636 while (Py_ISDIGIT((unsigned)*f)) {
2637 if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
2638 PyErr_SetString(PyExc_ValueError,
2639 "precision too big");
2640 return NULL;
2641 }
2642 precision = (precision * 10) + (*f - '0');
2643 f++;
2644 }
2645 }
Victor Stinner96865452011-03-01 23:44:09 +00002646 if (*f == '%') {
2647 /* "%.3%s" => f points to "3" */
2648 f--;
2649 }
2650 }
2651 if (*f == '\0') {
Victor Stinnere215d962012-10-06 23:03:36 +02002652 /* bogus format "%.123" => go backward, f points to "3" */
Victor Stinner96865452011-03-01 23:44:09 +00002653 f--;
2654 }
Victor Stinner96865452011-03-01 23:44:09 +00002655
2656 /* Handle %ld, %lu, %lld and %llu. */
2657 longflag = 0;
2658 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002659 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002660 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002661 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002662 longflag = 1;
2663 ++f;
2664 }
Victor Stinner96865452011-03-01 23:44:09 +00002665 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002666 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002667 longlongflag = 1;
2668 f += 2;
2669 }
Victor Stinner96865452011-03-01 23:44:09 +00002670 }
2671 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002672 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002673 size_tflag = 1;
2674 ++f;
2675 }
Victor Stinnere215d962012-10-06 23:03:36 +02002676
2677 if (f[1] == '\0')
2678 writer->overallocate = 0;
2679
2680 switch (*f) {
2681 case 'c':
2682 {
2683 int ordinal = va_arg(*vargs, int);
Victor Stinnerff5a8482012-10-06 23:05:45 +02002684 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Serhiy Storchakac89533f2013-06-23 20:21:16 +03002685 PyErr_SetString(PyExc_OverflowError,
Victor Stinnerff5a8482012-10-06 23:05:45 +02002686 "character argument not in range(0x110000)");
2687 return NULL;
2688 }
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002689 if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002690 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002691 break;
2692 }
2693
2694 case 'i':
2695 case 'd':
2696 case 'u':
2697 case 'x':
2698 {
2699 /* used by sprintf */
Victor Stinner15a11362012-10-06 23:48:20 +02002700 char buffer[MAX_LONG_LONG_CHARS];
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002701 Py_ssize_t arglen;
Victor Stinnere215d962012-10-06 23:03:36 +02002702
2703 if (*f == 'u') {
Victor Stinnere215d962012-10-06 23:03:36 +02002704 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002705 len = sprintf(buffer, "%lu",
Victor Stinnere215d962012-10-06 23:03:36 +02002706 va_arg(*vargs, unsigned long));
Victor Stinnere215d962012-10-06 23:03:36 +02002707 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002708 len = sprintf(buffer, "%llu",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002709 va_arg(*vargs, unsigned long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002710 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002711 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "u",
Victor Stinnere215d962012-10-06 23:03:36 +02002712 va_arg(*vargs, size_t));
2713 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002714 len = sprintf(buffer, "%u",
Victor Stinnere215d962012-10-06 23:03:36 +02002715 va_arg(*vargs, unsigned int));
2716 }
2717 else if (*f == 'x') {
Victor Stinner3aa979e2014-11-18 21:40:51 +01002718 len = sprintf(buffer, "%x", va_arg(*vargs, int));
Victor Stinnere215d962012-10-06 23:03:36 +02002719 }
2720 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002721 if (longflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002722 len = sprintf(buffer, "%li",
Victor Stinnere215d962012-10-06 23:03:36 +02002723 va_arg(*vargs, long));
Victor Stinnere215d962012-10-06 23:03:36 +02002724 else if (longlongflag)
Benjamin Peterson47ff0732016-09-08 09:15:54 -07002725 len = sprintf(buffer, "%lli",
Benjamin Petersonaf580df2016-09-06 10:46:49 -07002726 va_arg(*vargs, long long));
Victor Stinnere215d962012-10-06 23:03:36 +02002727 else if (size_tflag)
Victor Stinner3aa979e2014-11-18 21:40:51 +01002728 len = sprintf(buffer, "%" PY_FORMAT_SIZE_T "i",
Victor Stinnere215d962012-10-06 23:03:36 +02002729 va_arg(*vargs, Py_ssize_t));
2730 else
Victor Stinner3aa979e2014-11-18 21:40:51 +01002731 len = sprintf(buffer, "%i",
Victor Stinnere215d962012-10-06 23:03:36 +02002732 va_arg(*vargs, int));
2733 }
2734 assert(len >= 0);
2735
Victor Stinnere215d962012-10-06 23:03:36 +02002736 if (precision < len)
2737 precision = len;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002738
2739 arglen = Py_MAX(precision, width);
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002740 if (_PyUnicodeWriter_Prepare(writer, arglen, 127) == -1)
2741 return NULL;
2742
Victor Stinnere215d962012-10-06 23:03:36 +02002743 if (width > precision) {
2744 Py_UCS4 fillchar;
2745 fill = width - precision;
2746 fillchar = zeropad?'0':' ';
Victor Stinner15a11362012-10-06 23:48:20 +02002747 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, fillchar) == -1)
2748 return NULL;
2749 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002750 }
Victor Stinner15a11362012-10-06 23:48:20 +02002751 if (precision > len) {
Victor Stinnere215d962012-10-06 23:03:36 +02002752 fill = precision - len;
Victor Stinner15a11362012-10-06 23:48:20 +02002753 if (PyUnicode_Fill(writer->buffer, writer->pos, fill, '0') == -1)
2754 return NULL;
2755 writer->pos += fill;
Victor Stinnere215d962012-10-06 23:03:36 +02002756 }
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002757
Victor Stinner4a587072013-11-19 12:54:53 +01002758 if (_PyUnicodeWriter_WriteASCIIString(writer, buffer, len) < 0)
2759 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002760 break;
2761 }
2762
2763 case 'p':
2764 {
2765 char number[MAX_LONG_LONG_CHARS];
2766
2767 len = sprintf(number, "%p", va_arg(*vargs, void*));
2768 assert(len >= 0);
2769
2770 /* %p is ill-defined: ensure leading 0x. */
2771 if (number[1] == 'X')
2772 number[1] = 'x';
2773 else if (number[1] != 'x') {
2774 memmove(number + 2, number,
2775 strlen(number) + 1);
2776 number[0] = '0';
2777 number[1] = 'x';
2778 len += 2;
2779 }
2780
Victor Stinner4a587072013-11-19 12:54:53 +01002781 if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002782 return NULL;
2783 break;
2784 }
2785
2786 case 's':
2787 {
2788 /* UTF-8 */
2789 const char *s = va_arg(*vargs, const char*);
Victor Stinner998b8062018-09-12 00:23:25 +02002790 if (unicode_fromformat_write_cstr(writer, s, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002791 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002792 break;
2793 }
2794
2795 case 'U':
2796 {
2797 PyObject *obj = va_arg(*vargs, PyObject *);
2798 assert(obj && _PyUnicode_CHECK(obj));
2799
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002800 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002801 return NULL;
2802 break;
2803 }
2804
2805 case 'V':
2806 {
2807 PyObject *obj = va_arg(*vargs, PyObject *);
2808 const char *str = va_arg(*vargs, const char *);
Victor Stinnere215d962012-10-06 23:03:36 +02002809 if (obj) {
2810 assert(_PyUnicode_CHECK(obj));
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002811 if (unicode_fromformat_write_str(writer, obj, width, precision) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002812 return NULL;
2813 }
2814 else {
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002815 assert(str != NULL);
Victor Stinner998b8062018-09-12 00:23:25 +02002816 if (unicode_fromformat_write_cstr(writer, str, width, precision) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002817 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002818 }
2819 break;
2820 }
2821
2822 case 'S':
2823 {
2824 PyObject *obj = va_arg(*vargs, PyObject *);
2825 PyObject *str;
2826 assert(obj);
2827 str = PyObject_Str(obj);
2828 if (!str)
2829 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002830 if (unicode_fromformat_write_str(writer, str, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002831 Py_DECREF(str);
2832 return NULL;
2833 }
2834 Py_DECREF(str);
2835 break;
2836 }
2837
2838 case 'R':
2839 {
2840 PyObject *obj = va_arg(*vargs, PyObject *);
2841 PyObject *repr;
2842 assert(obj);
2843 repr = PyObject_Repr(obj);
2844 if (!repr)
2845 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002846 if (unicode_fromformat_write_str(writer, repr, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002847 Py_DECREF(repr);
2848 return NULL;
2849 }
2850 Py_DECREF(repr);
2851 break;
2852 }
2853
2854 case 'A':
2855 {
2856 PyObject *obj = va_arg(*vargs, PyObject *);
2857 PyObject *ascii;
2858 assert(obj);
2859 ascii = PyObject_ASCII(obj);
2860 if (!ascii)
2861 return NULL;
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002862 if (unicode_fromformat_write_str(writer, ascii, width, precision) == -1) {
Victor Stinnere215d962012-10-06 23:03:36 +02002863 Py_DECREF(ascii);
2864 return NULL;
2865 }
2866 Py_DECREF(ascii);
2867 break;
2868 }
2869
2870 case '%':
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02002871 if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002872 return NULL;
Victor Stinnere215d962012-10-06 23:03:36 +02002873 break;
2874
2875 default:
2876 /* if we stumble upon an unknown formatting code, copy the rest
2877 of the format string to the output string. (we cannot just
2878 skip the code, since there's no way to know what's in the
2879 argument list) */
2880 len = strlen(p);
Victor Stinner4a587072013-11-19 12:54:53 +01002881 if (_PyUnicodeWriter_WriteLatin1String(writer, p, len) == -1)
Victor Stinnere215d962012-10-06 23:03:36 +02002882 return NULL;
2883 f = p+len;
2884 return f;
2885 }
2886
2887 f++;
Victor Stinner96865452011-03-01 23:44:09 +00002888 return f;
2889}
2890
Walter Dörwaldd2034312007-05-18 16:29:38 +00002891PyObject *
2892PyUnicode_FromFormatV(const char *format, va_list vargs)
2893{
Victor Stinnere215d962012-10-06 23:03:36 +02002894 va_list vargs2;
2895 const char *f;
2896 _PyUnicodeWriter writer;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002897
Victor Stinner8f674cc2013-04-17 23:02:17 +02002898 _PyUnicodeWriter_Init(&writer);
2899 writer.min_length = strlen(format) + 100;
2900 writer.overallocate = 1;
Victor Stinnere215d962012-10-06 23:03:36 +02002901
Benjamin Peterson0c212142016-09-20 20:39:33 -07002902 // Copy varags to be able to pass a reference to a subfunction.
2903 va_copy(vargs2, vargs);
Victor Stinnere215d962012-10-06 23:03:36 +02002904
2905 for (f = format; *f; ) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002906 if (*f == '%') {
Victor Stinnere215d962012-10-06 23:03:36 +02002907 f = unicode_fromformat_arg(&writer, f, &vargs2);
2908 if (f == NULL)
2909 goto fail;
Victor Stinner1205f272010-09-11 00:54:47 +00002910 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002911 else {
Victor Stinnere215d962012-10-06 23:03:36 +02002912 const char *p;
2913 Py_ssize_t len;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002914
Victor Stinnere215d962012-10-06 23:03:36 +02002915 p = f;
2916 do
2917 {
2918 if ((unsigned char)*p > 127) {
2919 PyErr_Format(PyExc_ValueError,
2920 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2921 "string, got a non-ASCII byte: 0x%02x",
2922 (unsigned char)*p);
Victor Stinner1ddf53d2016-09-21 14:13:14 +02002923 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002924 }
2925 p++;
2926 }
2927 while (*p != '\0' && *p != '%');
2928 len = p - f;
2929
2930 if (*p == '\0')
2931 writer.overallocate = 0;
Victor Stinner4a587072013-11-19 12:54:53 +01002932
2933 if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
Victor Stinnere215d962012-10-06 23:03:36 +02002934 goto fail;
Victor Stinnere215d962012-10-06 23:03:36 +02002935
2936 f = p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002937 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002938 }
Christian Heimes2f2fee12016-09-21 11:37:27 +02002939 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002940 return _PyUnicodeWriter_Finish(&writer);
2941
2942 fail:
Christian Heimes2f2fee12016-09-21 11:37:27 +02002943 va_end(vargs2);
Victor Stinnere215d962012-10-06 23:03:36 +02002944 _PyUnicodeWriter_Dealloc(&writer);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002945 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002946}
2947
Walter Dörwaldd2034312007-05-18 16:29:38 +00002948PyObject *
2949PyUnicode_FromFormat(const char *format, ...)
2950{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002951 PyObject* ret;
2952 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002953
2954#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002955 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002956#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002957 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002958#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002959 ret = PyUnicode_FromFormatV(format, vargs);
2960 va_end(vargs);
2961 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002962}
2963
Serhiy Storchakac46db922018-10-23 22:58:24 +03002964static Py_ssize_t
2965unicode_get_widechar_size(PyObject *unicode)
2966{
2967 Py_ssize_t res;
2968
2969 assert(unicode != NULL);
2970 assert(_PyUnicode_CHECK(unicode));
2971
2972 if (_PyUnicode_WSTR(unicode) != NULL) {
2973 return PyUnicode_WSTR_LENGTH(unicode);
2974 }
2975 assert(PyUnicode_IS_READY(unicode));
2976
2977 res = _PyUnicode_LENGTH(unicode);
2978#if SIZEOF_WCHAR_T == 2
2979 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
2980 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
2981 const Py_UCS4 *end = s + res;
2982 for (; s < end; ++s) {
2983 if (*s > 0xFFFF) {
2984 ++res;
2985 }
2986 }
2987 }
2988#endif
2989 return res;
2990}
2991
2992static void
2993unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
2994{
2995 const wchar_t *wstr;
2996
2997 assert(unicode != NULL);
2998 assert(_PyUnicode_CHECK(unicode));
2999
3000 wstr = _PyUnicode_WSTR(unicode);
3001 if (wstr != NULL) {
3002 memcpy(w, wstr, size * sizeof(wchar_t));
3003 return;
3004 }
3005 assert(PyUnicode_IS_READY(unicode));
3006
3007 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3008 const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
3009 for (; size--; ++s, ++w) {
3010 *w = *s;
3011 }
3012 }
3013 else {
3014#if SIZEOF_WCHAR_T == 4
3015 assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
3016 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
3017 for (; size--; ++s, ++w) {
3018 *w = *s;
3019 }
3020#else
3021 assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
3022 const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
3023 for (; size--; ++s, ++w) {
3024 Py_UCS4 ch = *s;
3025 if (ch > 0xFFFF) {
3026 assert(ch <= MAX_UNICODE);
3027 /* encode surrogate pair in this case */
3028 *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
3029 if (!size--)
3030 break;
3031 *w = Py_UNICODE_LOW_SURROGATE(ch);
3032 }
3033 else {
3034 *w = ch;
3035 }
3036 }
3037#endif
3038 }
3039}
3040
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003041#ifdef HAVE_WCHAR_H
3042
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003043/* Convert a Unicode object to a wide character string.
Victor Stinner5593d8a2010-10-02 11:11:27 +00003044
Victor Stinnerd88d9832011-09-06 02:00:05 +02003045 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003046 character) required to convert the unicode object. Ignore size argument.
3047
Victor Stinnerd88d9832011-09-06 02:00:05 +02003048 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00003049 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02003050 the null character). */
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003051Py_ssize_t
3052PyUnicode_AsWideChar(PyObject *unicode,
3053 wchar_t *w,
3054 Py_ssize_t size)
Victor Stinner137c34c2010-09-29 10:25:54 +00003055{
Victor Stinner5593d8a2010-10-02 11:11:27 +00003056 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003057
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003058 if (unicode == NULL) {
3059 PyErr_BadInternalCall();
3060 return -1;
3061 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003062 if (!PyUnicode_Check(unicode)) {
3063 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003064 return -1;
Victor Stinner5593d8a2010-10-02 11:11:27 +00003065 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003066
3067 res = unicode_get_widechar_size(unicode);
3068 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003069 return res + 1;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003070 }
3071
3072 if (size > res) {
3073 size = res + 1;
3074 }
3075 else {
3076 res = size;
3077 }
3078 unicode_copy_as_widechar(unicode, w, size);
3079 return res;
Victor Stinner137c34c2010-09-29 10:25:54 +00003080}
3081
Victor Stinner137c34c2010-09-29 10:25:54 +00003082wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00003083PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00003084 Py_ssize_t *size)
3085{
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003086 wchar_t *buffer;
Victor Stinner137c34c2010-09-29 10:25:54 +00003087 Py_ssize_t buflen;
3088
3089 if (unicode == NULL) {
3090 PyErr_BadInternalCall();
3091 return NULL;
3092 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003093 if (!PyUnicode_Check(unicode)) {
3094 PyErr_BadArgument();
Serhiy Storchakae613e6a2017-06-27 16:03:14 +03003095 return NULL;
3096 }
3097
Serhiy Storchakac46db922018-10-23 22:58:24 +03003098 buflen = unicode_get_widechar_size(unicode);
3099 buffer = (wchar_t *) PyMem_NEW(wchar_t, (buflen + 1));
Victor Stinner137c34c2010-09-29 10:25:54 +00003100 if (buffer == NULL) {
3101 PyErr_NoMemory();
3102 return NULL;
3103 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003104 unicode_copy_as_widechar(unicode, buffer, buflen + 1);
3105 if (size != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00003106 *size = buflen;
Serhiy Storchakac46db922018-10-23 22:58:24 +03003107 }
3108 else if (wcslen(buffer) != (size_t)buflen) {
3109 PyMem_FREE(buffer);
3110 PyErr_SetString(PyExc_ValueError,
3111 "embedded null character");
3112 return NULL;
3113 }
Victor Stinner137c34c2010-09-29 10:25:54 +00003114 return buffer;
3115}
3116
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003117#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00003118
Alexander Belopolsky40018472011-02-26 01:02:56 +00003119PyObject *
3120PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003121{
Victor Stinner8faf8212011-12-08 22:14:11 +01003122 if (ordinal < 0 || ordinal > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003123 PyErr_SetString(PyExc_ValueError,
3124 "chr() arg not in range(0x110000)");
3125 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003126 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00003127
Victor Stinner985a82a2014-01-03 12:53:47 +01003128 return unicode_char((Py_UCS4)ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00003129}
3130
Alexander Belopolsky40018472011-02-26 01:02:56 +00003131PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003132PyUnicode_FromObject(PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003133{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003134 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00003135 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003136 if (PyUnicode_CheckExact(obj)) {
Benjamin Petersonbac79492012-01-14 13:34:47 -05003137 if (PyUnicode_READY(obj) == -1)
Victor Stinnerd3a83d52011-10-01 03:09:33 +02003138 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00003139 Py_INCREF(obj);
3140 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003141 }
3142 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003143 /* For a Unicode subtype that's not a Unicode object,
3144 return a true Unicode object with the same data. */
Victor Stinnerbf6e5602011-12-12 01:53:47 +01003145 return _PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003146 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00003147 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003148 "Can't convert '%.100s' object to str implicitly",
3149 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00003150 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003151}
3152
Alexander Belopolsky40018472011-02-26 01:02:56 +00003153PyObject *
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02003154PyUnicode_FromEncodedObject(PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003155 const char *encoding,
3156 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003157{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003158 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003159 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00003160
Guido van Rossumd57fd912000-03-10 22:53:23 +00003161 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003162 PyErr_BadInternalCall();
3163 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003164 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003165
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003166 /* Decoding bytes objects is the most common case and should be fast */
3167 if (PyBytes_Check(obj)) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003168 if (PyBytes_GET_SIZE(obj) == 0)
3169 _Py_RETURN_UNICODE_EMPTY();
3170 v = PyUnicode_Decode(
3171 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
3172 encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003173 return v;
3174 }
3175
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003176 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003177 PyErr_SetString(PyExc_TypeError,
3178 "decoding str is not supported");
3179 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00003180 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00003181
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003182 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
3183 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
3184 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003185 "decoding to str: need a bytes-like object, %.80s found",
3186 Py_TYPE(obj)->tp_name);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003187 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00003188 }
Tim Petersced69f82003-09-16 20:30:58 +00003189
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003190 if (buffer.len == 0) {
Serhiy Storchaka05997252013-01-26 12:14:02 +02003191 PyBuffer_Release(&buffer);
3192 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +00003193 }
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00003194
Serhiy Storchaka05997252013-01-26 12:14:02 +02003195 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Antoine Pitroub0fa8312010-09-01 15:10:12 +00003196 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00003197 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003198}
3199
Victor Stinnerebe17e02016-10-12 13:57:45 +02003200/* Normalize an encoding name: similar to encodings.normalize_encoding(), but
3201 also convert to lowercase. Return 1 on success, or 0 on error (encoding is
3202 longer than lower_len-1). */
Victor Stinnerd45c7f82012-12-04 01:34:47 +01003203int
3204_Py_normalize_encoding(const char *encoding,
3205 char *lower,
3206 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003207{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003208 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00003209 char *l;
3210 char *l_end;
Victor Stinner942889a2016-09-05 15:40:10 -07003211 int punct;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003212
Victor Stinner942889a2016-09-05 15:40:10 -07003213 assert(encoding != NULL);
3214
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003215 e = encoding;
3216 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00003217 l_end = &lower[lower_len - 1];
Victor Stinner942889a2016-09-05 15:40:10 -07003218 punct = 0;
3219 while (1) {
3220 char c = *e;
3221 if (c == 0) {
3222 break;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003223 }
Victor Stinner942889a2016-09-05 15:40:10 -07003224
3225 if (Py_ISALNUM(c) || c == '.') {
3226 if (punct && l != lower) {
3227 if (l == l_end) {
3228 return 0;
3229 }
3230 *l++ = '_';
3231 }
3232 punct = 0;
3233
3234 if (l == l_end) {
3235 return 0;
3236 }
3237 *l++ = Py_TOLOWER(c);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003238 }
3239 else {
Victor Stinner942889a2016-09-05 15:40:10 -07003240 punct = 1;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003241 }
Victor Stinner942889a2016-09-05 15:40:10 -07003242
3243 e++;
Guido van Rossumdaa251c2007-10-25 23:47:33 +00003244 }
3245 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00003246 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00003247}
3248
Alexander Belopolsky40018472011-02-26 01:02:56 +00003249PyObject *
3250PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003251 Py_ssize_t size,
3252 const char *encoding,
3253 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00003254{
3255 PyObject *buffer = NULL, *unicode;
3256 Py_buffer info;
Victor Stinner942889a2016-09-05 15:40:10 -07003257 char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
3258
3259 if (encoding == NULL) {
3260 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3261 }
Victor Stinner600d3be2010-06-10 12:00:55 +00003262
Fred Drakee4315f52000-05-09 19:53:39 +00003263 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003264 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3265 char *lower = buflower;
3266
3267 /* Fast paths */
3268 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3269 lower += 3;
3270 if (*lower == '_') {
3271 /* Match "utf8" and "utf_8" */
3272 lower++;
3273 }
3274
3275 if (lower[0] == '8' && lower[1] == 0) {
3276 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
3277 }
3278 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3279 return PyUnicode_DecodeUTF16(s, size, errors, 0);
3280 }
3281 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3282 return PyUnicode_DecodeUTF32(s, size, errors, 0);
3283 }
3284 }
3285 else {
3286 if (strcmp(lower, "ascii") == 0
3287 || strcmp(lower, "us_ascii") == 0) {
3288 return PyUnicode_DecodeASCII(s, size, errors);
3289 }
Steve Dowercc16be82016-09-08 10:35:16 -07003290 #ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003291 else if (strcmp(lower, "mbcs") == 0) {
3292 return PyUnicode_DecodeMBCS(s, size, errors);
3293 }
3294 #endif
3295 else if (strcmp(lower, "latin1") == 0
3296 || strcmp(lower, "latin_1") == 0
3297 || strcmp(lower, "iso_8859_1") == 0
3298 || strcmp(lower, "iso8859_1") == 0) {
3299 return PyUnicode_DecodeLatin1(s, size, errors);
3300 }
3301 }
Victor Stinner37296e82010-06-10 13:36:23 +00003302 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003303
3304 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003305 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00003306 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00003307 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00003308 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003309 if (buffer == NULL)
3310 goto onError;
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003311 unicode = _PyCodec_DecodeText(buffer, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003312 if (unicode == NULL)
3313 goto onError;
3314 if (!PyUnicode_Check(unicode)) {
3315 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003316 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003317 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003318 encoding,
3319 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003320 Py_DECREF(unicode);
3321 goto onError;
3322 }
3323 Py_DECREF(buffer);
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003324 return unicode_result(unicode);
Tim Petersced69f82003-09-16 20:30:58 +00003325
Benjamin Peterson29060642009-01-31 22:14:21 +00003326 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003327 Py_XDECREF(buffer);
3328 return NULL;
3329}
3330
Alexander Belopolsky40018472011-02-26 01:02:56 +00003331PyObject *
3332PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003333 const char *encoding,
3334 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003335{
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003336 if (!PyUnicode_Check(unicode)) {
3337 PyErr_BadArgument();
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003338 return NULL;
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003339 }
3340
Serhiy Storchaka00939072016-10-27 21:05:49 +03003341 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3342 "PyUnicode_AsDecodedObject() is deprecated; "
3343 "use PyCodec_Decode() to decode from str", 1) < 0)
3344 return NULL;
3345
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003346 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003347 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003348
3349 /* Decode via the codec registry */
Serhiy Storchaka77eede32016-10-25 10:07:51 +03003350 return PyCodec_Decode(unicode, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003351}
3352
Alexander Belopolsky40018472011-02-26 01:02:56 +00003353PyObject *
3354PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003355 const char *encoding,
3356 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003357{
3358 PyObject *v;
3359
3360 if (!PyUnicode_Check(unicode)) {
3361 PyErr_BadArgument();
3362 goto onError;
3363 }
3364
Serhiy Storchaka00939072016-10-27 21:05:49 +03003365 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3366 "PyUnicode_AsDecodedUnicode() is deprecated; "
3367 "use PyCodec_Decode() to decode from str to str", 1) < 0)
3368 return NULL;
3369
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003370 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003371 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003372
3373 /* Decode via the codec registry */
3374 v = PyCodec_Decode(unicode, encoding, errors);
3375 if (v == NULL)
3376 goto onError;
3377 if (!PyUnicode_Check(v)) {
3378 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003379 "'%.400s' decoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003380 "use codecs.decode() to decode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003381 encoding,
3382 Py_TYPE(unicode)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003383 Py_DECREF(v);
3384 goto onError;
3385 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01003386 return unicode_result(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003387
Benjamin Peterson29060642009-01-31 22:14:21 +00003388 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003389 return NULL;
3390}
3391
Alexander Belopolsky40018472011-02-26 01:02:56 +00003392PyObject *
3393PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003394 Py_ssize_t size,
3395 const char *encoding,
3396 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003397{
3398 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003399
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003400 unicode = PyUnicode_FromWideChar(s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003401 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003402 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003403 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3404 Py_DECREF(unicode);
3405 return v;
3406}
3407
Alexander Belopolsky40018472011-02-26 01:02:56 +00003408PyObject *
3409PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003410 const char *encoding,
3411 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003412{
3413 PyObject *v;
3414
3415 if (!PyUnicode_Check(unicode)) {
3416 PyErr_BadArgument();
3417 goto onError;
3418 }
3419
Serhiy Storchaka00939072016-10-27 21:05:49 +03003420 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3421 "PyUnicode_AsEncodedObject() is deprecated; "
3422 "use PyUnicode_AsEncodedString() to encode from str to bytes "
3423 "or PyCodec_Encode() for generic encoding", 1) < 0)
3424 return NULL;
3425
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003426 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003427 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003428
3429 /* Encode via the codec registry */
3430 v = PyCodec_Encode(unicode, encoding, errors);
3431 if (v == NULL)
3432 goto onError;
3433 return v;
3434
Benjamin Peterson29060642009-01-31 22:14:21 +00003435 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003436 return NULL;
3437}
3438
Victor Stinner1b579672011-12-17 05:47:23 +01003439
Victor Stinner2cba6b82018-01-10 22:46:15 +01003440static PyObject *
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003441unicode_encode_locale(PyObject *unicode, const char *errors,
3442 int current_locale)
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003443{
Victor Stinner3d4226a2018-08-29 22:21:32 +02003444 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003445
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003446 Py_ssize_t wlen;
3447 wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
3448 if (wstr == NULL) {
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003449 return NULL;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003450 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003451
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003452 if ((size_t)wlen != wcslen(wstr)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003453 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003454 PyMem_Free(wstr);
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003455 return NULL;
3456 }
3457
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003458 char *str;
3459 size_t error_pos;
3460 const char *reason;
3461 int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003462 current_locale, error_handler);
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003463 PyMem_Free(wstr);
3464
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003465 if (res != 0) {
3466 if (res == -2) {
3467 PyObject *exc;
3468 exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
3469 "locale", unicode,
3470 (Py_ssize_t)error_pos,
3471 (Py_ssize_t)(error_pos+1),
3472 reason);
3473 if (exc != NULL) {
3474 PyCodec_StrictErrors(exc);
3475 Py_DECREF(exc);
3476 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003477 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003478 else if (res == -3) {
3479 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3480 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003481 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003482 PyErr_NoMemory();
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003483 }
Victor Stinnerbde9d6b2018-11-28 10:26:20 +01003484 return NULL;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003485 }
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003486
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003487 PyObject *bytes = PyBytes_FromString(str);
3488 PyMem_RawFree(str);
3489 return bytes;
Victor Stinnerf2ea71f2011-12-17 04:13:41 +01003490}
3491
Victor Stinnerad158722010-10-27 00:25:46 +00003492PyObject *
Victor Stinner2cba6b82018-01-10 22:46:15 +01003493PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
3494{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003495 return unicode_encode_locale(unicode, errors, 1);
3496}
3497
3498PyObject *
Victor Stinnerad158722010-10-27 00:25:46 +00003499PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003500{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003501 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003502 const _PyCoreConfig *config = &interp->core_config;
3503#if defined(__APPLE__)
3504 return _PyUnicode_AsUTF8String(unicode, config->filesystem_errors);
3505#else
Victor Stinner793b5312011-04-27 00:24:21 +02003506 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3507 cannot use it to encode and decode filenames before it is loaded. Load
3508 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003509 implementation of the locale codec until the codec registry is
3510 initialized and the Python codec is loaded. See initfsencoding(). */
3511 if (interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003512 return PyUnicode_AsEncodedString(unicode,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003513 config->filesystem_encoding,
3514 config->filesystem_errors);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003515 }
3516 else {
Victor Stinner2cba6b82018-01-10 22:46:15 +01003517 return unicode_encode_locale(unicode,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003518 config->filesystem_errors, 0);
Victor Stinnerc39211f2010-09-29 16:35:47 +00003519 }
Victor Stinnerad158722010-10-27 00:25:46 +00003520#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003521}
3522
Alexander Belopolsky40018472011-02-26 01:02:56 +00003523PyObject *
3524PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003525 const char *encoding,
3526 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003527{
3528 PyObject *v;
Victor Stinner942889a2016-09-05 15:40:10 -07003529 char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003530
Guido van Rossumd57fd912000-03-10 22:53:23 +00003531 if (!PyUnicode_Check(unicode)) {
3532 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003533 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003534 }
Fred Drakee4315f52000-05-09 19:53:39 +00003535
Victor Stinner942889a2016-09-05 15:40:10 -07003536 if (encoding == NULL) {
3537 return _PyUnicode_AsUTF8String(unicode, errors);
3538 }
3539
Fred Drakee4315f52000-05-09 19:53:39 +00003540 /* Shortcuts for common default encodings */
Victor Stinner942889a2016-09-05 15:40:10 -07003541 if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
3542 char *lower = buflower;
3543
3544 /* Fast paths */
3545 if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
3546 lower += 3;
3547 if (*lower == '_') {
3548 /* Match "utf8" and "utf_8" */
3549 lower++;
3550 }
3551
3552 if (lower[0] == '8' && lower[1] == 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003553 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinner942889a2016-09-05 15:40:10 -07003554 }
3555 else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
3556 return _PyUnicode_EncodeUTF16(unicode, errors, 0);
3557 }
3558 else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
3559 return _PyUnicode_EncodeUTF32(unicode, errors, 0);
3560 }
Victor Stinnera5c68c32011-03-02 01:03:14 +00003561 }
Victor Stinner942889a2016-09-05 15:40:10 -07003562 else {
3563 if (strcmp(lower, "ascii") == 0
3564 || strcmp(lower, "us_ascii") == 0) {
3565 return _PyUnicode_AsASCIIString(unicode, errors);
3566 }
Steve Dowercc16be82016-09-08 10:35:16 -07003567#ifdef MS_WINDOWS
Victor Stinner942889a2016-09-05 15:40:10 -07003568 else if (strcmp(lower, "mbcs") == 0) {
3569 return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
3570 }
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003571#endif
Victor Stinner942889a2016-09-05 15:40:10 -07003572 else if (strcmp(lower, "latin1") == 0 ||
3573 strcmp(lower, "latin_1") == 0 ||
3574 strcmp(lower, "iso_8859_1") == 0 ||
3575 strcmp(lower, "iso8859_1") == 0) {
3576 return _PyUnicode_AsLatin1String(unicode, errors);
3577 }
3578 }
Victor Stinner37296e82010-06-10 13:36:23 +00003579 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003580
3581 /* Encode via the codec registry */
Nick Coghlanc72e4e62013-11-22 22:39:36 +10003582 v = _PyCodec_EncodeText(unicode, encoding, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003583 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003584 return NULL;
3585
3586 /* The normal path */
3587 if (PyBytes_Check(v))
3588 return v;
3589
3590 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003591 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003592 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003593 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003594
3595 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
Nick Coghlan8b097b42013-11-13 23:49:21 +10003596 "encoder %s returned bytearray instead of bytes; "
3597 "use codecs.encode() to encode to arbitrary types",
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003598 encoding);
3599 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003600 Py_DECREF(v);
3601 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003602 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003603
Serhiy Storchakafff9a312017-03-21 08:53:25 +02003604 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
3605 PyByteArray_GET_SIZE(v));
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003606 Py_DECREF(v);
3607 return b;
3608 }
3609
3610 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003611 "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003612 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003613 encoding,
3614 Py_TYPE(v)->tp_name);
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003615 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003616 return NULL;
3617}
3618
Alexander Belopolsky40018472011-02-26 01:02:56 +00003619PyObject *
3620PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003621 const char *encoding,
3622 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003623{
3624 PyObject *v;
3625
3626 if (!PyUnicode_Check(unicode)) {
3627 PyErr_BadArgument();
3628 goto onError;
3629 }
3630
Serhiy Storchaka00939072016-10-27 21:05:49 +03003631 if (PyErr_WarnEx(PyExc_DeprecationWarning,
3632 "PyUnicode_AsEncodedUnicode() is deprecated; "
3633 "use PyCodec_Encode() to encode from str to str", 1) < 0)
3634 return NULL;
3635
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003636 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003637 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003638
3639 /* Encode via the codec registry */
3640 v = PyCodec_Encode(unicode, encoding, errors);
3641 if (v == NULL)
3642 goto onError;
3643 if (!PyUnicode_Check(v)) {
3644 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003645 "'%.400s' encoder returned '%.400s' instead of 'str'; "
Nick Coghlan8b097b42013-11-13 23:49:21 +10003646 "use codecs.encode() to encode to arbitrary types",
Victor Stinner998b8062018-09-12 00:23:25 +02003647 encoding,
3648 Py_TYPE(v)->tp_name);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003649 Py_DECREF(v);
3650 goto onError;
3651 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003652 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003653
Benjamin Peterson29060642009-01-31 22:14:21 +00003654 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003655 return NULL;
3656}
3657
Victor Stinner2cba6b82018-01-10 22:46:15 +01003658static PyObject*
3659unicode_decode_locale(const char *str, Py_ssize_t len, const char *errors,
3660 int current_locale)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003661{
Victor Stinner3d4226a2018-08-29 22:21:32 +02003662 _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003663
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003664 if (str[len] != '\0' || (size_t)len != strlen(str)) {
3665 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003666 return NULL;
3667 }
3668
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003669 wchar_t *wstr;
3670 size_t wlen;
3671 const char *reason;
3672 int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
Victor Stinner3d4226a2018-08-29 22:21:32 +02003673 current_locale, error_handler);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003674 if (res != 0) {
3675 if (res == -2) {
3676 PyObject *exc;
3677 exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
3678 "locale", str, len,
3679 (Py_ssize_t)wlen,
3680 (Py_ssize_t)(wlen + 1),
3681 reason);
3682 if (exc != NULL) {
3683 PyCodec_StrictErrors(exc);
3684 Py_DECREF(exc);
3685 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003686 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02003687 else if (res == -3) {
3688 PyErr_SetString(PyExc_ValueError, "unsupported error handler");
3689 }
Victor Stinner2cba6b82018-01-10 22:46:15 +01003690 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003691 PyErr_NoMemory();
Victor Stinner2cba6b82018-01-10 22:46:15 +01003692 }
Victor Stinner2f197072011-12-17 07:08:30 +01003693 return NULL;
Victor Stinner2f197072011-12-17 07:08:30 +01003694 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003695
3696 PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
3697 PyMem_RawFree(wstr);
3698 return unicode;
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003699}
3700
3701PyObject*
Victor Stinner2cba6b82018-01-10 22:46:15 +01003702PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
3703 const char *errors)
3704{
Victor Stinner2cba6b82018-01-10 22:46:15 +01003705 return unicode_decode_locale(str, len, errors, 1);
3706}
3707
3708PyObject*
Victor Stinner1b579672011-12-17 05:47:23 +01003709PyUnicode_DecodeLocale(const char *str, const char *errors)
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003710{
3711 Py_ssize_t size = (Py_ssize_t)strlen(str);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003712 return unicode_decode_locale(str, size, errors, 1);
Victor Stinneraf02e1c2011-12-16 23:56:01 +01003713}
3714
3715
3716PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003717PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003718 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003719 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3720}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003721
Christian Heimes5894ba72007-11-04 11:43:14 +00003722PyObject*
3723PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3724{
Victor Stinnercaba55b2018-08-03 15:33:52 +02003725 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003726 const _PyCoreConfig *config = &interp->core_config;
3727#if defined(__APPLE__)
3728 return PyUnicode_DecodeUTF8Stateful(s, size, config->filesystem_errors, NULL);
3729#else
Victor Stinner793b5312011-04-27 00:24:21 +02003730 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3731 cannot use it to encode and decode filenames before it is loaded. Load
3732 the Python codec requires to encode at least its own filename. Use the C
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003733 implementation of the locale codec until the codec registry is
3734 initialized and the Python codec is loaded. See initfsencoding(). */
3735 if (interp->fscodec_initialized) {
Steve Dower78057b42016-11-06 19:35:08 -08003736 return PyUnicode_Decode(s, size,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003737 config->filesystem_encoding,
3738 config->filesystem_errors);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003739 }
3740 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01003741 return unicode_decode_locale(s, size,
Victor Stinnerb2457ef2018-08-29 13:25:36 +02003742 config->filesystem_errors, 0);
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003743 }
Victor Stinnerad158722010-10-27 00:25:46 +00003744#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003745}
3746
Martin v. Löwis011e8422009-05-05 04:43:17 +00003747
3748int
3749PyUnicode_FSConverter(PyObject* arg, void* addr)
3750{
Brett Cannonec6ce872016-09-06 15:50:29 -07003751 PyObject *path = NULL;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003752 PyObject *output = NULL;
3753 Py_ssize_t size;
3754 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003755 if (arg == NULL) {
3756 Py_DECREF(*(PyObject**)addr);
Benjamin Petersona4d33b32015-11-15 21:57:39 -08003757 *(PyObject**)addr = NULL;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003758 return 1;
3759 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003760 path = PyOS_FSPath(arg);
3761 if (path == NULL) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003762 return 0;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003763 }
Brett Cannonec6ce872016-09-06 15:50:29 -07003764 if (PyBytes_Check(path)) {
3765 output = path;
3766 }
3767 else { // PyOS_FSPath() guarantees its returned value is bytes or str.
3768 output = PyUnicode_EncodeFSDefault(path);
3769 Py_DECREF(path);
3770 if (!output) {
3771 return 0;
3772 }
3773 assert(PyBytes_Check(output));
3774 }
3775
Victor Stinner0ea2a462010-04-30 00:22:08 +00003776 size = PyBytes_GET_SIZE(output);
3777 data = PyBytes_AS_STRING(output);
Victor Stinner12174a52014-08-15 23:17:38 +02003778 if ((size_t)size != strlen(data)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003779 PyErr_SetString(PyExc_ValueError, "embedded null byte");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003780 Py_DECREF(output);
3781 return 0;
3782 }
3783 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003784 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003785}
3786
3787
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003788int
3789PyUnicode_FSDecoder(PyObject* arg, void* addr)
3790{
Brett Cannona5711202016-09-06 19:36:01 -07003791 int is_buffer = 0;
3792 PyObject *path = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003793 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003794 if (arg == NULL) {
3795 Py_DECREF(*(PyObject**)addr);
Serhiy Storchaka40db90c2017-04-20 21:19:31 +03003796 *(PyObject**)addr = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003797 return 1;
3798 }
Brett Cannona5711202016-09-06 19:36:01 -07003799
3800 is_buffer = PyObject_CheckBuffer(arg);
3801 if (!is_buffer) {
3802 path = PyOS_FSPath(arg);
3803 if (path == NULL) {
Serhiy Storchakafebc3322016-08-06 23:29:29 +03003804 return 0;
3805 }
Brett Cannona5711202016-09-06 19:36:01 -07003806 }
3807 else {
3808 path = arg;
3809 Py_INCREF(arg);
3810 }
3811
3812 if (PyUnicode_Check(path)) {
Brett Cannona5711202016-09-06 19:36:01 -07003813 output = path;
3814 }
3815 else if (PyBytes_Check(path) || is_buffer) {
3816 PyObject *path_bytes = NULL;
3817
3818 if (!PyBytes_Check(path) &&
3819 PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
Victor Stinner998b8062018-09-12 00:23:25 +02003820 "path should be string, bytes, or os.PathLike, not %.200s",
3821 Py_TYPE(arg)->tp_name)) {
3822 Py_DECREF(path);
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003823 return 0;
Brett Cannona5711202016-09-06 19:36:01 -07003824 }
3825 path_bytes = PyBytes_FromObject(path);
3826 Py_DECREF(path);
3827 if (!path_bytes) {
3828 return 0;
3829 }
3830 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path_bytes),
3831 PyBytes_GET_SIZE(path_bytes));
3832 Py_DECREF(path_bytes);
3833 if (!output) {
3834 return 0;
3835 }
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003836 }
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003837 else {
3838 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02003839 "path should be string, bytes, or os.PathLike, not %.200s",
3840 Py_TYPE(arg)->tp_name);
Brett Cannona5711202016-09-06 19:36:01 -07003841 Py_DECREF(path);
Serhiy Storchaka9305d832016-06-18 13:53:36 +03003842 return 0;
3843 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05003844 if (PyUnicode_READY(output) == -1) {
Victor Stinner065836e2011-10-27 01:56:33 +02003845 Py_DECREF(output);
3846 return 0;
3847 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003848 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003849 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03003850 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003851 Py_DECREF(output);
3852 return 0;
3853 }
3854 *(PyObject**)addr = output;
3855 return Py_CLEANUP_SUPPORTED;
3856}
3857
3858
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003859const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003860PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003861{
Christian Heimesf3863112007-11-22 07:46:41 +00003862 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003863
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003864 if (!PyUnicode_Check(unicode)) {
3865 PyErr_BadArgument();
3866 return NULL;
3867 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003868 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003869 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003870
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003871 if (PyUnicode_UTF8(unicode) == NULL) {
3872 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03003873 bytes = _PyUnicode_AsUTF8String(unicode, NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003874 if (bytes == NULL)
3875 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003876 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3877 if (_PyUnicode_UTF8(unicode) == NULL) {
Victor Stinnera5afb582013-10-29 01:28:23 +01003878 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003879 Py_DECREF(bytes);
3880 return NULL;
3881 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003882 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
Christian Heimesf051e432016-09-13 20:22:02 +02003883 memcpy(_PyUnicode_UTF8(unicode),
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003884 PyBytes_AS_STRING(bytes),
3885 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003886 Py_DECREF(bytes);
3887 }
3888
3889 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003890 *psize = PyUnicode_UTF8_LENGTH(unicode);
3891 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003892}
3893
Serhiy Storchaka2a404b62017-01-22 23:07:07 +02003894const char *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003895PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003896{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003897 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3898}
3899
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003900Py_UNICODE *
3901PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3902{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003903 if (!PyUnicode_Check(unicode)) {
3904 PyErr_BadArgument();
3905 return NULL;
3906 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003907 Py_UNICODE *w = _PyUnicode_WSTR(unicode);
3908 if (w == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003909 /* Non-ASCII compact unicode object */
Serhiy Storchakac46db922018-10-23 22:58:24 +03003910 assert(_PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003911 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003912
Serhiy Storchakac46db922018-10-23 22:58:24 +03003913 Py_ssize_t wlen = unicode_get_widechar_size(unicode);
3914 if ((size_t)wlen > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
3915 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003916 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003917 }
Serhiy Storchakac46db922018-10-23 22:58:24 +03003918 w = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) * (wlen + 1));
3919 if (w == NULL) {
3920 PyErr_NoMemory();
3921 return NULL;
3922 }
3923 unicode_copy_as_widechar(unicode, w, wlen + 1);
3924 _PyUnicode_WSTR(unicode) = w;
3925 if (!PyUnicode_IS_COMPACT_ASCII(unicode)) {
3926 _PyUnicode_WSTR_LENGTH(unicode) = wlen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003927 }
3928 }
3929 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003930 *size = PyUnicode_WSTR_LENGTH(unicode);
Serhiy Storchakac46db922018-10-23 22:58:24 +03003931 return w;
Martin v. Löwis5b222132007-06-10 09:51:05 +00003932}
3933
Alexander Belopolsky40018472011-02-26 01:02:56 +00003934Py_UNICODE *
3935PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003936{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003937 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003938}
3939
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03003940const Py_UNICODE *
3941_PyUnicode_AsUnicode(PyObject *unicode)
3942{
3943 Py_ssize_t size;
3944 const Py_UNICODE *wstr;
3945
3946 wstr = PyUnicode_AsUnicodeAndSize(unicode, &size);
3947 if (wstr && wcslen(wstr) != (size_t)size) {
3948 PyErr_SetString(PyExc_ValueError, "embedded null character");
3949 return NULL;
3950 }
3951 return wstr;
3952}
3953
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003954
Alexander Belopolsky40018472011-02-26 01:02:56 +00003955Py_ssize_t
3956PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003957{
3958 if (!PyUnicode_Check(unicode)) {
3959 PyErr_BadArgument();
3960 goto onError;
3961 }
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02003962 if (_PyUnicode_WSTR(unicode) == NULL) {
3963 if (PyUnicode_AsUnicode(unicode) == NULL)
3964 goto onError;
3965 }
3966 return PyUnicode_WSTR_LENGTH(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003967
Benjamin Peterson29060642009-01-31 22:14:21 +00003968 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003969 return -1;
3970}
3971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003972Py_ssize_t
3973PyUnicode_GetLength(PyObject *unicode)
3974{
Victor Stinner07621332012-06-16 04:53:46 +02003975 if (!PyUnicode_Check(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003976 PyErr_BadArgument();
3977 return -1;
3978 }
Victor Stinner07621332012-06-16 04:53:46 +02003979 if (PyUnicode_READY(unicode) == -1)
3980 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003981 return PyUnicode_GET_LENGTH(unicode);
3982}
3983
3984Py_UCS4
3985PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3986{
Victor Stinner69ed0f42013-04-09 21:48:24 +02003987 void *data;
3988 int kind;
3989
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003990 if (!PyUnicode_Check(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003991 PyErr_BadArgument();
3992 return (Py_UCS4)-1;
3993 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +03003994 if (PyUnicode_READY(unicode) == -1) {
3995 return (Py_UCS4)-1;
3996 }
Victor Stinnerc4b49542011-12-11 22:44:26 +01003997 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003998 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003999 return (Py_UCS4)-1;
4000 }
Victor Stinner69ed0f42013-04-09 21:48:24 +02004001 data = PyUnicode_DATA(unicode);
4002 kind = PyUnicode_KIND(unicode);
4003 return PyUnicode_READ(kind, data, index);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004004}
4005
4006int
4007PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
4008{
4009 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004010 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011 return -1;
4012 }
Victor Stinner488fa492011-12-12 00:01:39 +01004013 assert(PyUnicode_IS_READY(unicode));
Victor Stinnerc4b49542011-12-11 22:44:26 +01004014 if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02004015 PyErr_SetString(PyExc_IndexError, "string index out of range");
4016 return -1;
4017 }
Victor Stinner488fa492011-12-12 00:01:39 +01004018 if (unicode_check_modifiable(unicode))
Victor Stinnercd9950f2011-10-02 00:34:53 +02004019 return -1;
Victor Stinnerc9590ad2012-03-04 01:34:37 +01004020 if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
4021 PyErr_SetString(PyExc_ValueError, "character out of range");
4022 return -1;
4023 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004024 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
4025 index, ch);
4026 return 0;
4027}
4028
Alexander Belopolsky40018472011-02-26 01:02:56 +00004029const char *
4030PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00004031{
Victor Stinner42cb4622010-09-01 19:39:01 +00004032 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00004033}
4034
Victor Stinner554f3f02010-06-16 23:33:54 +00004035/* create or adjust a UnicodeDecodeError */
4036static void
4037make_decode_exception(PyObject **exceptionObject,
4038 const char *encoding,
4039 const char *input, Py_ssize_t length,
4040 Py_ssize_t startpos, Py_ssize_t endpos,
4041 const char *reason)
4042{
4043 if (*exceptionObject == NULL) {
4044 *exceptionObject = PyUnicodeDecodeError_Create(
4045 encoding, input, length, startpos, endpos, reason);
4046 }
4047 else {
4048 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
4049 goto onError;
4050 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
4051 goto onError;
4052 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
4053 goto onError;
4054 }
4055 return;
4056
4057onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02004058 Py_CLEAR(*exceptionObject);
Victor Stinner554f3f02010-06-16 23:33:54 +00004059}
4060
Steve Dowercc16be82016-09-08 10:35:16 -07004061#ifdef MS_WINDOWS
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004062/* error handling callback helper:
4063 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00004064 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004065 and adjust various state variables.
4066 return 0 on success, -1 on error
4067*/
4068
Alexander Belopolsky40018472011-02-26 01:02:56 +00004069static int
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004070unicode_decode_call_errorhandler_wchar(
4071 const char *errors, PyObject **errorHandler,
4072 const char *encoding, const char *reason,
4073 const char **input, const char **inend, Py_ssize_t *startinpos,
4074 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4075 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004076{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004077 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004078
4079 PyObject *restuple = NULL;
4080 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01004081 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004082 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004083 Py_ssize_t requiredsize;
4084 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004085 PyObject *inputobj = NULL;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004086 wchar_t *repwstr;
4087 Py_ssize_t repwlen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004088
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004089 assert (_PyUnicode_KIND(*output) == PyUnicode_WCHAR_KIND);
4090 outsize = _PyUnicode_WSTR_LENGTH(*output);
Victor Stinner596a6c42011-11-09 00:02:18 +01004091
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004092 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004093 *errorHandler = PyCodec_LookupError(errors);
4094 if (*errorHandler == NULL)
4095 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004096 }
4097
Victor Stinner554f3f02010-06-16 23:33:54 +00004098 make_decode_exception(exceptionObject,
4099 encoding,
4100 *input, *inend - *input,
4101 *startinpos, *endinpos,
4102 reason);
4103 if (*exceptionObject == NULL)
4104 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004105
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004106 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004107 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00004108 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004109 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004110 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00004111 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004112 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004113 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004114 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004115
4116 /* Copy back the bytes variables, which might have been modified by the
4117 callback */
4118 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4119 if (!inputobj)
4120 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004121 *input = PyBytes_AS_STRING(inputobj);
4122 insize = PyBytes_GET_SIZE(inputobj);
4123 *inend = *input + insize;
4124 /* we can DECREF safely, as the exception has another reference,
4125 so the object won't go away. */
4126 Py_DECREF(inputobj);
4127
4128 if (newpos<0)
4129 newpos = insize+newpos;
4130 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004131 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004132 goto onError;
4133 }
4134
4135 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
4136 if (repwstr == NULL)
4137 goto onError;
4138 /* need more space? (at least enough for what we
4139 have+the replacement+the rest of the string (starting
4140 at the new input position), so we won't have to check space
4141 when there are no errors in the rest of the string) */
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004142 requiredsize = *outpos;
4143 if (requiredsize > PY_SSIZE_T_MAX - repwlen)
4144 goto overflow;
4145 requiredsize += repwlen;
4146 if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
4147 goto overflow;
4148 requiredsize += insize - newpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004149 if (requiredsize > outsize) {
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004150 if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004151 requiredsize = 2*outsize;
4152 if (unicode_resize(output, requiredsize) < 0)
4153 goto onError;
4154 }
4155 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
4156 *outpos += repwlen;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004157 *endinpos = newpos;
4158 *inptr = *input + newpos;
4159
4160 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004161 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004162 return 0;
4163
Benjamin Peterson2b76ce62014-09-29 18:50:06 -04004164 overflow:
4165 PyErr_SetString(PyExc_OverflowError,
4166 "decoded result is too long for a Python string");
4167
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004168 onError:
4169 Py_XDECREF(restuple);
4170 return -1;
4171}
Steve Dowercc16be82016-09-08 10:35:16 -07004172#endif /* MS_WINDOWS */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004173
4174static int
4175unicode_decode_call_errorhandler_writer(
4176 const char *errors, PyObject **errorHandler,
4177 const char *encoding, const char *reason,
4178 const char **input, const char **inend, Py_ssize_t *startinpos,
4179 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
4180 _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
4181{
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004182 static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004183
4184 PyObject *restuple = NULL;
4185 PyObject *repunicode = NULL;
4186 Py_ssize_t insize;
4187 Py_ssize_t newpos;
Victor Stinner170ca6f2013-04-18 00:25:28 +02004188 Py_ssize_t replen;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004189 Py_ssize_t remain;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004190 PyObject *inputobj = NULL;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004191 int need_to_grow = 0;
4192 const char *new_inptr;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004193
4194 if (*errorHandler == NULL) {
4195 *errorHandler = PyCodec_LookupError(errors);
4196 if (*errorHandler == NULL)
4197 goto onError;
4198 }
4199
4200 make_decode_exception(exceptionObject,
4201 encoding,
4202 *input, *inend - *input,
4203 *startinpos, *endinpos,
4204 reason);
4205 if (*exceptionObject == NULL)
4206 goto onError;
4207
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01004208 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004209 if (restuple == NULL)
4210 goto onError;
4211 if (!PyTuple_Check(restuple)) {
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004212 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004213 goto onError;
4214 }
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004215 if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004216 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004217
4218 /* Copy back the bytes variables, which might have been modified by the
4219 callback */
4220 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
4221 if (!inputobj)
4222 goto onError;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004223 remain = *inend - *input - *endinpos;
Christian Heimes72b710a2008-05-26 13:28:38 +00004224 *input = PyBytes_AS_STRING(inputobj);
4225 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004226 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00004227 /* we can DECREF safely, as the exception has another reference,
4228 so the object won't go away. */
4229 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00004230
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004231 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004232 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004233 if (newpos<0 || newpos>insize) {
Victor Stinnera33bce02014-07-04 22:47:46 +02004234 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00004235 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00004236 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004237
Victor Stinner170ca6f2013-04-18 00:25:28 +02004238 replen = PyUnicode_GET_LENGTH(repunicode);
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004239 if (replen > 1) {
4240 writer->min_length += replen - 1;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004241 need_to_grow = 1;
4242 }
4243 new_inptr = *input + newpos;
4244 if (*inend - new_inptr > remain) {
4245 /* We don't know the decoding algorithm here so we make the worst
4246 assumption that one byte decodes to one unicode character.
4247 If unfortunately one byte could decode to more unicode characters,
4248 the decoder may write out-of-bound then. Is it possible for the
4249 algorithms using this function? */
4250 writer->min_length += *inend - new_inptr - remain;
4251 need_to_grow = 1;
4252 }
4253 if (need_to_grow) {
Victor Stinner8f674cc2013-04-17 23:02:17 +02004254 writer->overallocate = 1;
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02004255 if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
Serhiy Storchaka7e4b9052015-01-26 01:22:54 +02004256 PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
4257 goto onError;
4258 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004259 if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
Victor Stinner376cfa12013-04-17 23:58:16 +02004260 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004261
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004262 *endinpos = newpos;
Xiang Zhang2c7fd462018-01-31 20:48:05 +08004263 *inptr = new_inptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00004264
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004265 /* we made it! */
Serhiy Storchaka523c4492016-10-22 23:18:31 +03004266 Py_DECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004267 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004268
Benjamin Peterson29060642009-01-31 22:14:21 +00004269 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004270 Py_XDECREF(restuple);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004271 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004272}
4273
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004274/* --- UTF-7 Codec -------------------------------------------------------- */
4275
Antoine Pitrou244651a2009-05-04 18:56:13 +00004276/* See RFC2152 for details. We encode conservatively and decode liberally. */
4277
4278/* Three simple macros defining base-64. */
4279
4280/* Is c a base-64 character? */
4281
4282#define IS_BASE64(c) \
4283 (((c) >= 'A' && (c) <= 'Z') || \
4284 ((c) >= 'a' && (c) <= 'z') || \
4285 ((c) >= '0' && (c) <= '9') || \
4286 (c) == '+' || (c) == '/')
4287
4288/* given that c is a base-64 character, what is its base-64 value? */
4289
4290#define FROM_BASE64(c) \
4291 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
4292 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
4293 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
4294 (c) == '+' ? 62 : 63)
4295
4296/* What is the base-64 character of the bottom 6 bits of n? */
4297
4298#define TO_BASE64(n) \
4299 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
4300
4301/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
4302 * decoded as itself. We are permissive on decoding; the only ASCII
4303 * byte not decoding to itself is the + which begins a base64
4304 * string. */
4305
4306#define DECODE_DIRECT(c) \
4307 ((c) <= 127 && (c) != '+')
4308
4309/* The UTF-7 encoder treats ASCII characters differently according to
4310 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
4311 * the above). See RFC2152. This array identifies these different
4312 * sets:
4313 * 0 : "Set D"
4314 * alphanumeric and '(),-./:?
4315 * 1 : "Set O"
4316 * !"#$%&*;<=>@[]^_`{|}
4317 * 2 : "whitespace"
4318 * ht nl cr sp
4319 * 3 : special (must be base64 encoded)
4320 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
4321 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004322
Tim Petersced69f82003-09-16 20:30:58 +00004323static
Antoine Pitrou244651a2009-05-04 18:56:13 +00004324char utf7_category[128] = {
4325/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
4326 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
4327/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
4328 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4329/* sp ! " # $ % & ' ( ) * + , - . / */
4330 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
4331/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
4332 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
4333/* @ A B C D E F G H I J K L M N O */
4334 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4335/* P Q R S T U V W X Y Z [ \ ] ^ _ */
4336 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
4337/* ` a b c d e f g h i j k l m n o */
4338 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4339/* p q r s t u v w x y z { | } ~ del */
4340 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004341};
4342
Antoine Pitrou244651a2009-05-04 18:56:13 +00004343/* ENCODE_DIRECT: this character should be encoded as itself. The
4344 * answer depends on whether we are encoding set O as itself, and also
4345 * on whether we are encoding whitespace as itself. RFC2152 makes it
4346 * clear that the answers to these questions vary between
4347 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00004348
Antoine Pitrou244651a2009-05-04 18:56:13 +00004349#define ENCODE_DIRECT(c, directO, directWS) \
4350 ((c) < 128 && (c) > 0 && \
4351 ((utf7_category[(c)] == 0) || \
4352 (directWS && (utf7_category[(c)] == 2)) || \
4353 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004354
Alexander Belopolsky40018472011-02-26 01:02:56 +00004355PyObject *
4356PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004357 Py_ssize_t size,
4358 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004359{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004360 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
4361}
4362
Antoine Pitrou244651a2009-05-04 18:56:13 +00004363/* The decoder. The only state we preserve is our read position,
4364 * i.e. how many characters we have consumed. So if we end in the
4365 * middle of a shift sequence we have to back off the read position
4366 * and the output to the beginning of the sequence, otherwise we lose
4367 * all the shift state (seen bits, number of bits seen, high
4368 * surrogate). */
4369
Alexander Belopolsky40018472011-02-26 01:02:56 +00004370PyObject *
4371PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004372 Py_ssize_t size,
4373 const char *errors,
4374 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004375{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004376 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004377 Py_ssize_t startinpos;
4378 Py_ssize_t endinpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004379 const char *e;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004380 _PyUnicodeWriter writer;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004381 const char *errmsg = "";
4382 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004383 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004384 unsigned int base64bits = 0;
4385 unsigned long base64buffer = 0;
Victor Stinner24729f32011-11-10 20:31:37 +01004386 Py_UCS4 surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004387 PyObject *errorHandler = NULL;
4388 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004389
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004390 if (size == 0) {
4391 if (consumed)
4392 *consumed = 0;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02004393 _Py_RETURN_UNICODE_EMPTY();
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004394 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004395
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004396 /* Start off assuming it's all ASCII. Widen later as necessary. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02004397 _PyUnicodeWriter_Init(&writer);
4398 writer.min_length = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004399
4400 shiftOutStart = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004401 e = s + size;
4402
4403 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004404 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00004406 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004407
Antoine Pitrou244651a2009-05-04 18:56:13 +00004408 if (inShift) { /* in a base-64 section */
4409 if (IS_BASE64(ch)) { /* consume a base-64 character */
4410 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
4411 base64bits += 6;
4412 s++;
4413 if (base64bits >= 16) {
4414 /* we have enough bits for a UTF-16 value */
Victor Stinner24729f32011-11-10 20:31:37 +01004415 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00004416 base64bits -= 16;
4417 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004418 assert(outCh <= 0xffff);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004419 if (surrogate) {
4420 /* expecting a second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004421 if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
4422 Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004423 if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004424 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004425 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01004426 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004427 }
4428 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004429 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
Antoine Pitrou78edf752011-11-15 01:44:16 +01004430 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004431 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004432 }
4433 }
Victor Stinner551ac952011-11-29 22:58:13 +01004434 if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004435 /* first surrogate */
4436 surrogate = outCh;
4437 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004438 else {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004439 if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004440 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004441 }
4442 }
4443 }
4444 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004445 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004446 if (base64bits > 0) { /* left-over bits */
4447 if (base64bits >= 6) {
4448 /* We've seen at least one base-64 character */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004449 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004450 errmsg = "partial character in shift sequence";
4451 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004452 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004453 else {
4454 /* Some bits remain; they should be zero */
4455 if (base64buffer != 0) {
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004456 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004457 errmsg = "non-zero padding bits in shift sequence";
4458 goto utf7Error;
4459 }
4460 }
4461 }
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004462 if (surrogate && DECODE_DIRECT(ch)) {
4463 if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
4464 goto onError;
4465 }
4466 surrogate = 0;
4467 if (ch == '-') {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004468 /* '-' is absorbed; other terminating
4469 characters are preserved */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004470 s++;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004471 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004472 }
4473 }
4474 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004475 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004476 s++; /* consume '+' */
4477 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004478 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004479 if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004480 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004481 }
Zackery Spytze349bf22018-08-18 22:43:38 -06004482 else if (s < e && !IS_BASE64(*s)) {
4483 s++;
4484 errmsg = "ill-formed sequence";
4485 goto utf7Error;
4486 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004487 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004488 inShift = 1;
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004489 surrogate = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004490 shiftOutStart = writer.pos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004491 base64bits = 0;
Serhiy Storchaka35804e42013-10-19 20:38:19 +03004492 base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004493 }
4494 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004495 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004496 s++;
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004497 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004498 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004499 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004500 else {
4501 startinpos = s-starts;
4502 s++;
4503 errmsg = "unexpected special character";
4504 goto utf7Error;
4505 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004506 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004507utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004508 endinpos = s-starts;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004509 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 errors, &errorHandler,
4511 "utf7", errmsg,
4512 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004513 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00004514 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004515 }
4516
Antoine Pitrou244651a2009-05-04 18:56:13 +00004517 /* end of string */
4518
4519 if (inShift && !consumed) { /* in shift sequence, no more to follow */
4520 /* if we're in an inconsistent state, that's an error */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03004521 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004522 if (surrogate ||
4523 (base64bits >= 6) ||
4524 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004525 endinpos = size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004526 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrou244651a2009-05-04 18:56:13 +00004527 errors, &errorHandler,
4528 "utf7", "unterminated shift sequence",
4529 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004530 &writer))
Antoine Pitrou244651a2009-05-04 18:56:13 +00004531 goto onError;
4532 if (s < e)
4533 goto restart;
4534 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004535 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004536
4537 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004538 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00004539 if (inShift) {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004540 *consumed = startinpos;
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004541 if (writer.pos != shiftOutStart && writer.maxchar > 127) {
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004542 PyObject *result = PyUnicode_FromKindAndData(
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004543 writer.kind, writer.data, shiftOutStart);
4544 Py_XDECREF(errorHandler);
4545 Py_XDECREF(exc);
4546 _PyUnicodeWriter_Dealloc(&writer);
4547 return result;
Serhiy Storchaka016a3f32014-02-08 14:01:29 +02004548 }
Serhiy Storchaka6cbf1512014-02-08 14:06:33 +02004549 writer.pos = shiftOutStart; /* back off output */
Antoine Pitrou244651a2009-05-04 18:56:13 +00004550 }
4551 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004552 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004553 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004554 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004555
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004556 Py_XDECREF(errorHandler);
4557 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004558 return _PyUnicodeWriter_Finish(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004559
Benjamin Peterson29060642009-01-31 22:14:21 +00004560 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004561 Py_XDECREF(errorHandler);
4562 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004563 _PyUnicodeWriter_Dealloc(&writer);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004564 return NULL;
4565}
4566
4567
Alexander Belopolsky40018472011-02-26 01:02:56 +00004568PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004569_PyUnicode_EncodeUTF7(PyObject *str,
4570 int base64SetO,
4571 int base64WhiteSpace,
4572 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004573{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004574 int kind;
4575 void *data;
4576 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004577 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004578 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004579 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004580 unsigned int base64bits = 0;
4581 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004582 char * out;
4583 char * start;
4584
Benjamin Petersonbac79492012-01-14 13:34:47 -05004585 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004586 return NULL;
4587 kind = PyUnicode_KIND(str);
4588 data = PyUnicode_DATA(str);
4589 len = PyUnicode_GET_LENGTH(str);
4590
4591 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004592 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004593
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004594 /* It might be possible to tighten this worst case */
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004595 if (len > PY_SSIZE_T_MAX / 8)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004596 return PyErr_NoMemory();
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01004597 v = PyBytes_FromStringAndSize(NULL, len * 8);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004598 if (v == NULL)
4599 return NULL;
4600
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004601 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004602 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004603 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004604
Antoine Pitrou244651a2009-05-04 18:56:13 +00004605 if (inShift) {
4606 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4607 /* shifting out */
4608 if (base64bits) { /* output remaining bits */
4609 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4610 base64buffer = 0;
4611 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004612 }
4613 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004614 /* Characters not in the BASE64 set implicitly unshift the sequence
4615 so no '-' is required, except if the character is itself a '-' */
4616 if (IS_BASE64(ch) || ch == '-') {
4617 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004618 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004619 *out++ = (char) ch;
4620 }
4621 else {
4622 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004623 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004624 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004625 else { /* not in a shift sequence */
4626 if (ch == '+') {
4627 *out++ = '+';
4628 *out++ = '-';
4629 }
4630 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4631 *out++ = (char) ch;
4632 }
4633 else {
4634 *out++ = '+';
4635 inShift = 1;
4636 goto encode_char;
4637 }
4638 }
4639 continue;
4640encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004641 if (ch >= 0x10000) {
Victor Stinner8faf8212011-12-08 22:14:11 +01004642 assert(ch <= MAX_UNICODE);
Victor Stinner0d3721d2011-11-22 03:27:53 +01004643
Antoine Pitrou244651a2009-05-04 18:56:13 +00004644 /* code first surrogate */
4645 base64bits += 16;
Victor Stinner76df43d2012-10-30 01:42:39 +01004646 base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004647 while (base64bits >= 6) {
4648 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4649 base64bits -= 6;
4650 }
4651 /* prepare second surrogate */
Victor Stinner551ac952011-11-29 22:58:13 +01004652 ch = Py_UNICODE_LOW_SURROGATE(ch);
Antoine Pitrou244651a2009-05-04 18:56:13 +00004653 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004654 base64bits += 16;
4655 base64buffer = (base64buffer << 16) | ch;
4656 while (base64bits >= 6) {
4657 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4658 base64bits -= 6;
4659 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004660 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004661 if (base64bits)
4662 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4663 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004664 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004665 if (_PyBytes_Resize(&v, out - start) < 0)
4666 return NULL;
4667 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004668}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004669PyObject *
4670PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4671 Py_ssize_t size,
4672 int base64SetO,
4673 int base64WhiteSpace,
4674 const char *errors)
4675{
4676 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02004677 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004678 if (tmp == NULL)
4679 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004680 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004681 base64WhiteSpace, errors);
4682 Py_DECREF(tmp);
4683 return result;
4684}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004685
Antoine Pitrou244651a2009-05-04 18:56:13 +00004686#undef IS_BASE64
4687#undef FROM_BASE64
4688#undef TO_BASE64
4689#undef DECODE_DIRECT
4690#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004691
Guido van Rossumd57fd912000-03-10 22:53:23 +00004692/* --- UTF-8 Codec -------------------------------------------------------- */
4693
Alexander Belopolsky40018472011-02-26 01:02:56 +00004694PyObject *
4695PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004696 Py_ssize_t size,
4697 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004698{
Walter Dörwald69652032004-09-07 20:24:22 +00004699 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4700}
4701
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004702#include "stringlib/asciilib.h"
4703#include "stringlib/codecs.h"
4704#include "stringlib/undef.h"
4705
Antoine Pitrou0a3229d2011-11-21 20:39:13 +01004706#include "stringlib/ucs1lib.h"
4707#include "stringlib/codecs.h"
4708#include "stringlib/undef.h"
4709
4710#include "stringlib/ucs2lib.h"
4711#include "stringlib/codecs.h"
4712#include "stringlib/undef.h"
4713
4714#include "stringlib/ucs4lib.h"
4715#include "stringlib/codecs.h"
4716#include "stringlib/undef.h"
4717
Antoine Pitrouab868312009-01-10 15:40:25 +00004718/* Mask to quickly check whether a C 'long' contains a
4719 non-ASCII, UTF8-encoded char. */
4720#if (SIZEOF_LONG == 8)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004721# define ASCII_CHAR_MASK 0x8080808080808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004722#elif (SIZEOF_LONG == 4)
Mark Dickinson01ac8b62012-07-07 14:08:48 +02004723# define ASCII_CHAR_MASK 0x80808080UL
Antoine Pitrouab868312009-01-10 15:40:25 +00004724#else
4725# error C 'long' size should be either 4 or 8!
4726#endif
4727
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004728static Py_ssize_t
4729ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004730{
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004731 const char *p = start;
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004732 const char *aligned_end = (const char *) _Py_ALIGN_DOWN(end, SIZEOF_LONG);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004733
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004734 /*
4735 * Issue #17237: m68k is a bit different from most architectures in
4736 * that objects do not use "natural alignment" - for example, int and
4737 * long are only aligned at 2-byte boundaries. Therefore the assert()
4738 * won't work; also, tests have shown that skipping the "optimised
4739 * version" will even speed up m68k.
4740 */
4741#if !defined(__m68k__)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004742#if SIZEOF_LONG <= SIZEOF_VOID_P
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004743 assert(_Py_IS_ALIGNED(dest, SIZEOF_LONG));
4744 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004745 /* Fast path, see in STRINGLIB(utf8_decode) for
4746 an explanation. */
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004747 /* Help allocation */
4748 const char *_p = p;
4749 Py_UCS1 * q = dest;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004750 while (_p < aligned_end) {
4751 unsigned long value = *(const unsigned long *) _p;
4752 if (value & ASCII_CHAR_MASK)
Benjamin Peterson29060642009-01-31 22:14:21 +00004753 break;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004754 *((unsigned long *)q) = value;
4755 _p += SIZEOF_LONG;
4756 q += SIZEOF_LONG;
Benjamin Peterson14339b62009-01-31 16:36:08 +00004757 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004758 p = _p;
4759 while (p < end) {
4760 if ((unsigned char)*p & 0x80)
4761 break;
4762 *q++ = *p++;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004763 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004764 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004765 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004766#endif
Antoine Pitrou8b0e9842013-05-11 15:58:34 +02004767#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004768 while (p < end) {
4769 /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
4770 for an explanation. */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02004771 if (_Py_IS_ALIGNED(p, SIZEOF_LONG)) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02004772 /* Help allocation */
4773 const char *_p = p;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004774 while (_p < aligned_end) {
4775 unsigned long value = *(unsigned long *) _p;
4776 if (value & ASCII_CHAR_MASK)
4777 break;
4778 _p += SIZEOF_LONG;
4779 }
4780 p = _p;
4781 if (_p == end)
4782 break;
4783 }
4784 if ((unsigned char)*p & 0x80)
4785 break;
4786 ++p;
4787 }
4788 memcpy(dest, start, p - start);
4789 return p - start;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004790}
Antoine Pitrouab868312009-01-10 15:40:25 +00004791
Victor Stinner785938e2011-12-11 20:09:03 +01004792PyObject *
4793PyUnicode_DecodeUTF8Stateful(const char *s,
4794 Py_ssize_t size,
4795 const char *errors,
4796 Py_ssize_t *consumed)
4797{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004798 _PyUnicodeWriter writer;
Victor Stinner785938e2011-12-11 20:09:03 +01004799 const char *starts = s;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004800 const char *end = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004801
4802 Py_ssize_t startinpos;
4803 Py_ssize_t endinpos;
4804 const char *errmsg = "";
Victor Stinner1d65d912015-10-05 13:43:50 +02004805 PyObject *error_handler_obj = NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004806 PyObject *exc = NULL;
Victor Stinner1d65d912015-10-05 13:43:50 +02004807 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner785938e2011-12-11 20:09:03 +01004808
4809 if (size == 0) {
4810 if (consumed)
4811 *consumed = 0;
Serhiy Storchaka678db842013-01-26 12:16:36 +02004812 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner785938e2011-12-11 20:09:03 +01004813 }
4814
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004815 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
4816 if (size == 1 && (unsigned char)s[0] < 128) {
Victor Stinner785938e2011-12-11 20:09:03 +01004817 if (consumed)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004818 *consumed = 1;
4819 return get_latin1_char((unsigned char)s[0]);
Victor Stinner785938e2011-12-11 20:09:03 +01004820 }
4821
Victor Stinner8f674cc2013-04-17 23:02:17 +02004822 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02004823 writer.min_length = size;
4824 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004825 goto onError;
Victor Stinner785938e2011-12-11 20:09:03 +01004826
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004827 writer.pos = ascii_decode(s, end, writer.data);
4828 s += writer.pos;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004829 while (s < end) {
4830 Py_UCS4 ch;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004831 int kind = writer.kind;
Victor Stinner1d65d912015-10-05 13:43:50 +02004832
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004833 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004834 if (PyUnicode_IS_ASCII(writer.buffer))
4835 ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004836 else
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004837 ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004838 } else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004839 ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004840 } else {
4841 assert(kind == PyUnicode_4BYTE_KIND);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004842 ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004843 }
4844
4845 switch (ch) {
4846 case 0:
4847 if (s == end || consumed)
4848 goto End;
4849 errmsg = "unexpected end of data";
4850 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004851 endinpos = end - starts;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004852 break;
4853 case 1:
4854 errmsg = "invalid start byte";
4855 startinpos = s - starts;
4856 endinpos = startinpos + 1;
4857 break;
4858 case 2:
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004859 case 3:
4860 case 4:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004861 errmsg = "invalid continuation byte";
4862 startinpos = s - starts;
Ezio Melottif7ed5d12012-11-04 23:21:38 +02004863 endinpos = startinpos + ch - 1;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004864 break;
4865 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02004866 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004867 goto onError;
4868 continue;
4869 }
4870
Victor Stinner1d65d912015-10-05 13:43:50 +02004871 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02004872 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner1d65d912015-10-05 13:43:50 +02004873
4874 switch (error_handler) {
4875 case _Py_ERROR_IGNORE:
4876 s += (endinpos - startinpos);
4877 break;
4878
4879 case _Py_ERROR_REPLACE:
4880 if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
4881 goto onError;
4882 s += (endinpos - startinpos);
4883 break;
4884
4885 case _Py_ERROR_SURROGATEESCAPE:
Victor Stinner74e8fac2015-10-05 13:49:26 +02004886 {
4887 Py_ssize_t i;
4888
Victor Stinner1d65d912015-10-05 13:43:50 +02004889 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
4890 goto onError;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004891 for (i=startinpos; i<endinpos; i++) {
Victor Stinner1d65d912015-10-05 13:43:50 +02004892 ch = (Py_UCS4)(unsigned char)(starts[i]);
4893 PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
4894 ch + 0xdc00);
4895 writer.pos++;
4896 }
4897 s += (endinpos - startinpos);
4898 break;
Victor Stinner74e8fac2015-10-05 13:49:26 +02004899 }
Victor Stinner1d65d912015-10-05 13:43:50 +02004900
4901 default:
4902 if (unicode_decode_call_errorhandler_writer(
4903 errors, &error_handler_obj,
4904 "utf-8", errmsg,
4905 &starts, &end, &startinpos, &endinpos, &exc, &s,
4906 &writer))
4907 goto onError;
4908 }
Victor Stinner785938e2011-12-11 20:09:03 +01004909 }
4910
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004911End:
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004912 if (consumed)
4913 *consumed = s - starts;
4914
Victor Stinner1d65d912015-10-05 13:43:50 +02004915 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004916 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004917 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004918
4919onError:
Victor Stinner1d65d912015-10-05 13:43:50 +02004920 Py_XDECREF(error_handler_obj);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004921 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01004922 _PyUnicodeWriter_Dealloc(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004923 return NULL;
Victor Stinner785938e2011-12-11 20:09:03 +01004924}
4925
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004926
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004927/* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
4928 non-zero, use strict error handler otherwise.
Victor Stinner0d92c4f2012-11-12 23:32:21 +01004929
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004930 On success, write a pointer to a newly allocated wide character string into
4931 *wstr (use PyMem_RawFree() to free the memory) and write the output length
4932 (in number of wchar_t units) into *wlen (if wlen is set).
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004933
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004934 On memory allocation failure, return -1.
4935
4936 On decoding error (if surrogateescape is zero), return -2. If wlen is
4937 non-NULL, write the start of the illegal byte sequence into *wlen. If reason
4938 is not NULL, write the decoding error message into *reason. */
4939int
4940_Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
Victor Stinner3d4226a2018-08-29 22:21:32 +02004941 const char **reason, _Py_error_handler errors)
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004942{
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004943 const char *orig_s = s;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004944 const char *e;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004945 wchar_t *unicode;
4946 Py_ssize_t outpos;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004947
Victor Stinner3d4226a2018-08-29 22:21:32 +02004948 int surrogateescape = 0;
4949 int surrogatepass = 0;
4950 switch (errors)
4951 {
4952 case _Py_ERROR_STRICT:
4953 break;
4954 case _Py_ERROR_SURROGATEESCAPE:
4955 surrogateescape = 1;
4956 break;
4957 case _Py_ERROR_SURROGATEPASS:
4958 surrogatepass = 1;
4959 break;
4960 default:
4961 return -3;
4962 }
4963
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004964 /* Note: size will always be longer than the resulting Unicode
4965 character count */
Victor Stinner91106cd2017-12-13 12:29:09 +01004966 if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) < (size + 1)) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004967 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004968 }
4969
Victor Stinner6f8eeee2013-07-07 22:57:45 +02004970 unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
Victor Stinner91106cd2017-12-13 12:29:09 +01004971 if (!unicode) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004972 return -1;
Victor Stinner91106cd2017-12-13 12:29:09 +01004973 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004974
4975 /* Unpack UTF-8 encoded data */
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004976 e = s + size;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004977 outpos = 0;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004978 while (s < e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004979 Py_UCS4 ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004980#if SIZEOF_WCHAR_T == 4
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004981 ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004982#else
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004983 ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004984#endif
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004985 if (ch > 0xFF) {
4986#if SIZEOF_WCHAR_T == 4
Barry Warsawb2e57942017-09-14 18:13:16 -07004987 Py_UNREACHABLE();
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004988#else
Serhiy Storchakab6266432016-11-12 14:28:06 +02004989 assert(ch > 0xFFFF && ch <= MAX_UNICODE);
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004990 /* write a surrogate pair */
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004991 unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
4992 unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
4993#endif
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004994 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004995 else {
Victor Stinner3d4226a2018-08-29 22:21:32 +02004996 if (!ch && s == e) {
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02004997 break;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01004998 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02004999
5000 if (surrogateescape) {
5001 unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
5002 }
5003 else {
5004 /* Is it a valid three-byte code? */
5005 if (surrogatepass
5006 && (e - s) >= 3
5007 && (s[0] & 0xf0) == 0xe0
5008 && (s[1] & 0xc0) == 0x80
5009 && (s[2] & 0xc0) == 0x80)
5010 {
5011 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
5012 s += 3;
5013 unicode[outpos++] = ch;
5014 }
5015 else {
5016 PyMem_RawFree(unicode );
5017 if (reason != NULL) {
5018 switch (ch) {
5019 case 0:
5020 *reason = "unexpected end of data";
5021 break;
5022 case 1:
5023 *reason = "invalid start byte";
5024 break;
5025 /* 2, 3, 4 */
5026 default:
5027 *reason = "invalid continuation byte";
5028 break;
5029 }
5030 }
5031 if (wlen != NULL) {
5032 *wlen = s - orig_s;
5033 }
5034 return -2;
5035 }
5036 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005037 }
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005038 }
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02005039 unicode[outpos] = L'\0';
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005040 if (wlen) {
5041 *wlen = outpos;
Victor Stinner91106cd2017-12-13 12:29:09 +01005042 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005043 *wstr = unicode;
5044 return 0;
5045}
5046
5047wchar_t*
5048_Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen)
5049{
5050 wchar_t *wstr;
5051 int res = _Py_DecodeUTF8Ex(arg, arglen, &wstr, NULL, NULL, 1);
5052 if (res != 0) {
5053 return NULL;
5054 }
5055 return wstr;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00005056}
5057
Antoine Pitrouab868312009-01-10 15:40:25 +00005058
Victor Stinnere47e6982017-12-21 15:45:16 +01005059/* UTF-8 encoder using the surrogateescape error handler .
5060
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005061 On success, return 0 and write the newly allocated character string (use
5062 PyMem_Free() to free the memory) into *str.
Victor Stinnere47e6982017-12-21 15:45:16 +01005063
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005064 On encoding failure, return -2 and write the position of the invalid
5065 surrogate character into *error_pos (if error_pos is set) and the decoding
5066 error message into *reason (if reason is set).
Victor Stinnere47e6982017-12-21 15:45:16 +01005067
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005068 On memory allocation failure, return -1. */
5069int
5070_Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
Victor Stinner3d4226a2018-08-29 22:21:32 +02005071 const char **reason, int raw_malloc, _Py_error_handler errors)
Victor Stinnere47e6982017-12-21 15:45:16 +01005072{
5073 const Py_ssize_t max_char_size = 4;
5074 Py_ssize_t len = wcslen(text);
5075
5076 assert(len >= 0);
5077
Victor Stinner3d4226a2018-08-29 22:21:32 +02005078 int surrogateescape = 0;
5079 int surrogatepass = 0;
5080 switch (errors)
5081 {
5082 case _Py_ERROR_STRICT:
5083 break;
5084 case _Py_ERROR_SURROGATEESCAPE:
5085 surrogateescape = 1;
5086 break;
5087 case _Py_ERROR_SURROGATEPASS:
5088 surrogatepass = 1;
5089 break;
5090 default:
5091 return -3;
5092 }
5093
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005094 if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
5095 return -1;
5096 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005097 char *bytes;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005098 if (raw_malloc) {
5099 bytes = PyMem_RawMalloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005100 }
5101 else {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005102 bytes = PyMem_Malloc((len + 1) * max_char_size);
Victor Stinnere47e6982017-12-21 15:45:16 +01005103 }
5104 if (bytes == NULL) {
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005105 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005106 }
5107
5108 char *p = bytes;
5109 Py_ssize_t i;
Victor Stinner3d4226a2018-08-29 22:21:32 +02005110 for (i = 0; i < len; ) {
5111 Py_ssize_t ch_pos = i;
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005112 Py_UCS4 ch = text[i];
Victor Stinner3d4226a2018-08-29 22:21:32 +02005113 i++;
5114#if Py_UNICODE_SIZE == 2
5115 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
5116 && i < len
5117 && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
5118 {
5119 ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
5120 i++;
5121 }
5122#endif
Victor Stinnere47e6982017-12-21 15:45:16 +01005123
5124 if (ch < 0x80) {
5125 /* Encode ASCII */
5126 *p++ = (char) ch;
5127
5128 }
5129 else if (ch < 0x0800) {
5130 /* Encode Latin-1 */
5131 *p++ = (char)(0xc0 | (ch >> 6));
5132 *p++ = (char)(0x80 | (ch & 0x3f));
5133 }
Victor Stinner3d4226a2018-08-29 22:21:32 +02005134 else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005135 /* surrogateescape error handler */
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005136 if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
Victor Stinnere47e6982017-12-21 15:45:16 +01005137 if (error_pos != NULL) {
Victor Stinner3d4226a2018-08-29 22:21:32 +02005138 *error_pos = (size_t)ch_pos;
Victor Stinnere47e6982017-12-21 15:45:16 +01005139 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005140 if (reason != NULL) {
5141 *reason = "encoding error";
5142 }
5143 if (raw_malloc) {
5144 PyMem_RawFree(bytes);
5145 }
5146 else {
5147 PyMem_Free(bytes);
5148 }
5149 return -2;
Victor Stinnere47e6982017-12-21 15:45:16 +01005150 }
5151 *p++ = (char)(ch & 0xff);
5152 }
5153 else if (ch < 0x10000) {
5154 *p++ = (char)(0xe0 | (ch >> 12));
5155 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5156 *p++ = (char)(0x80 | (ch & 0x3f));
5157 }
5158 else { /* ch >= 0x10000 */
5159 assert(ch <= MAX_UNICODE);
5160 /* Encode UCS4 Unicode ordinals */
5161 *p++ = (char)(0xf0 | (ch >> 18));
5162 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
5163 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
5164 *p++ = (char)(0x80 | (ch & 0x3f));
5165 }
5166 }
5167 *p++ = '\0';
5168
5169 size_t final_size = (p - bytes);
Victor Stinner9dd76202017-12-21 16:20:32 +01005170 char *bytes2;
5171 if (raw_malloc) {
5172 bytes2 = PyMem_RawRealloc(bytes, final_size);
5173 }
5174 else {
5175 bytes2 = PyMem_Realloc(bytes, final_size);
5176 }
Victor Stinnere47e6982017-12-21 15:45:16 +01005177 if (bytes2 == NULL) {
5178 if (error_pos != NULL) {
5179 *error_pos = (size_t)-1;
5180 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005181 if (raw_malloc) {
5182 PyMem_RawFree(bytes);
5183 }
5184 else {
5185 PyMem_Free(bytes);
5186 }
5187 return -1;
Victor Stinnere47e6982017-12-21 15:45:16 +01005188 }
Victor Stinner7ed7aea2018-01-15 10:45:49 +01005189 *str = bytes2;
5190 return 0;
Victor Stinnere47e6982017-12-21 15:45:16 +01005191}
5192
5193
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005194/* Primary internal function which creates utf8 encoded bytes objects.
5195
5196 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00005197 and allocate exactly as much space needed at the end. Else allocate the
5198 maximum possible needed (4 result bytes per Unicode character), and return
5199 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00005200*/
Tim Peters7e3d9612002-04-21 03:26:37 +00005201PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01005202_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005203{
Victor Stinner6099a032011-12-18 14:22:26 +01005204 enum PyUnicode_Kind kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005205 void *data;
5206 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00005207
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005208 if (!PyUnicode_Check(unicode)) {
5209 PyErr_BadArgument();
5210 return NULL;
5211 }
5212
5213 if (PyUnicode_READY(unicode) == -1)
5214 return NULL;
5215
Victor Stinnere90fe6a2011-10-01 16:48:13 +02005216 if (PyUnicode_UTF8(unicode))
5217 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
5218 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005219
5220 kind = PyUnicode_KIND(unicode);
5221 data = PyUnicode_DATA(unicode);
5222 size = PyUnicode_GET_LENGTH(unicode);
5223
Benjamin Petersonead6b532011-12-20 17:23:42 -06005224 switch (kind) {
Victor Stinner6099a032011-12-18 14:22:26 +01005225 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07005226 Py_UNREACHABLE();
Victor Stinner6099a032011-12-18 14:22:26 +01005227 case PyUnicode_1BYTE_KIND:
5228 /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
5229 assert(!PyUnicode_IS_ASCII(unicode));
5230 return ucs1lib_utf8_encoder(unicode, data, size, errors);
5231 case PyUnicode_2BYTE_KIND:
5232 return ucs2lib_utf8_encoder(unicode, data, size, errors);
5233 case PyUnicode_4BYTE_KIND:
5234 return ucs4lib_utf8_encoder(unicode, data, size, errors);
Tim Peters602f7402002-04-27 18:03:26 +00005235 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005236}
5237
Alexander Belopolsky40018472011-02-26 01:02:56 +00005238PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005239PyUnicode_EncodeUTF8(const Py_UNICODE *s,
5240 Py_ssize_t size,
5241 const char *errors)
5242{
5243 PyObject *v, *unicode;
5244
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005245 unicode = PyUnicode_FromWideChar(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005246 if (unicode == NULL)
5247 return NULL;
5248 v = _PyUnicode_AsUTF8String(unicode, errors);
5249 Py_DECREF(unicode);
5250 return v;
5251}
5252
5253PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005254PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005255{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005256 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005257}
5258
Walter Dörwald41980ca2007-08-16 21:55:45 +00005259/* --- UTF-32 Codec ------------------------------------------------------- */
5260
5261PyObject *
5262PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005263 Py_ssize_t size,
5264 const char *errors,
5265 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005266{
5267 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
5268}
5269
5270PyObject *
5271PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005272 Py_ssize_t size,
5273 const char *errors,
5274 int *byteorder,
5275 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005276{
5277 const char *starts = s;
5278 Py_ssize_t startinpos;
5279 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005280 _PyUnicodeWriter writer;
Mark Dickinson7db923c2010-06-12 09:10:14 +00005281 const unsigned char *q, *e;
Victor Stinnere64322e2012-10-30 23:12:47 +01005282 int le, bo = 0; /* assume native ordering by default */
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005283 const char *encoding;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005284 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00005285 PyObject *errorHandler = NULL;
5286 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00005287
Walter Dörwald41980ca2007-08-16 21:55:45 +00005288 q = (unsigned char *)s;
5289 e = q + size;
5290
5291 if (byteorder)
5292 bo = *byteorder;
5293
5294 /* Check for BOM marks (U+FEFF) in the input and adjust current
5295 byte order setting accordingly. In native mode, the leading BOM
5296 mark is skipped, in all other modes, it is copied to the output
5297 stream as-is (giving a ZWNBSP character). */
Victor Stinnere64322e2012-10-30 23:12:47 +01005298 if (bo == 0 && size >= 4) {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005299 Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005300 if (bom == 0x0000FEFF) {
5301 bo = -1;
5302 q += 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005303 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005304 else if (bom == 0xFFFE0000) {
5305 bo = 1;
5306 q += 4;
5307 }
5308 if (byteorder)
5309 *byteorder = bo;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005310 }
5311
Victor Stinnere64322e2012-10-30 23:12:47 +01005312 if (q == e) {
5313 if (consumed)
5314 *consumed = size;
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005315 _Py_RETURN_UNICODE_EMPTY();
Walter Dörwald41980ca2007-08-16 21:55:45 +00005316 }
5317
Victor Stinnere64322e2012-10-30 23:12:47 +01005318#ifdef WORDS_BIGENDIAN
5319 le = bo < 0;
5320#else
5321 le = bo <= 0;
5322#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005323 encoding = le ? "utf-32-le" : "utf-32-be";
Victor Stinnere64322e2012-10-30 23:12:47 +01005324
Victor Stinner8f674cc2013-04-17 23:02:17 +02005325 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005326 writer.min_length = (e - q + 3) / 4;
5327 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005328 goto onError;
Victor Stinnere64322e2012-10-30 23:12:47 +01005329
Victor Stinnere64322e2012-10-30 23:12:47 +01005330 while (1) {
5331 Py_UCS4 ch = 0;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005332 Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00005333
Victor Stinnere64322e2012-10-30 23:12:47 +01005334 if (e - q >= 4) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005335 enum PyUnicode_Kind kind = writer.kind;
5336 void *data = writer.data;
Victor Stinnere64322e2012-10-30 23:12:47 +01005337 const unsigned char *last = e - 4;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005338 Py_ssize_t pos = writer.pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005339 if (le) {
5340 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005341 ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
Victor Stinnere64322e2012-10-30 23:12:47 +01005342 if (ch > maxch)
5343 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005344 if (kind != PyUnicode_1BYTE_KIND &&
5345 Py_UNICODE_IS_SURROGATE(ch))
5346 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005347 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005348 q += 4;
5349 } while (q <= last);
5350 }
5351 else {
5352 do {
Benjamin Peterson33d2a492016-09-06 20:40:04 -07005353 ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
Victor Stinnere64322e2012-10-30 23:12:47 +01005354 if (ch > maxch)
5355 break;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005356 if (kind != PyUnicode_1BYTE_KIND &&
5357 Py_UNICODE_IS_SURROGATE(ch))
5358 break;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005359 PyUnicode_WRITE(kind, data, pos++, ch);
Victor Stinnere64322e2012-10-30 23:12:47 +01005360 q += 4;
5361 } while (q <= last);
5362 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005363 writer.pos = pos;
Victor Stinnere64322e2012-10-30 23:12:47 +01005364 }
5365
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005366 if (Py_UNICODE_IS_SURROGATE(ch)) {
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005367 errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005368 startinpos = ((const char *)q) - starts;
5369 endinpos = startinpos + 4;
5370 }
5371 else if (ch <= maxch) {
Victor Stinnere64322e2012-10-30 23:12:47 +01005372 if (q == e || consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 break;
Victor Stinnere64322e2012-10-30 23:12:47 +01005374 /* remaining bytes at the end? (size should be divisible by 4) */
Benjamin Peterson29060642009-01-31 22:14:21 +00005375 errmsg = "truncated data";
Victor Stinnere64322e2012-10-30 23:12:47 +01005376 startinpos = ((const char *)q) - starts;
5377 endinpos = ((const char *)e) - starts;
Benjamin Peterson29060642009-01-31 22:14:21 +00005378 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005379 else {
5380 if (ch < 0x110000) {
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005381 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinnere64322e2012-10-30 23:12:47 +01005382 goto onError;
5383 q += 4;
5384 continue;
5385 }
Serhiy Storchakad3faf432015-01-18 11:28:37 +02005386 errmsg = "code point not in range(0x110000)";
Victor Stinnere64322e2012-10-30 23:12:47 +01005387 startinpos = ((const char *)q) - starts;
5388 endinpos = startinpos + 4;
Benjamin Peterson29060642009-01-31 22:14:21 +00005389 }
Victor Stinnere64322e2012-10-30 23:12:47 +01005390
5391 /* The remaining input chars are ignored if the callback
5392 chooses to skip the input */
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005393 if (unicode_decode_call_errorhandler_writer(
Benjamin Peterson29060642009-01-31 22:14:21 +00005394 errors, &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005395 encoding, errmsg,
Benjamin Peterson29060642009-01-31 22:14:21 +00005396 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005397 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005398 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005399 }
5400
Walter Dörwald41980ca2007-08-16 21:55:45 +00005401 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005402 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005403
Walter Dörwald41980ca2007-08-16 21:55:45 +00005404 Py_XDECREF(errorHandler);
5405 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005406 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005407
Benjamin Peterson29060642009-01-31 22:14:21 +00005408 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005409 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005410 Py_XDECREF(errorHandler);
5411 Py_XDECREF(exc);
5412 return NULL;
5413}
5414
5415PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005416_PyUnicode_EncodeUTF32(PyObject *str,
5417 const char *errors,
5418 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005419{
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005420 enum PyUnicode_Kind kind;
5421 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005422 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005423 PyObject *v;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005424 uint32_t *out;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005425#if PY_LITTLE_ENDIAN
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005426 int native_ordering = byteorder <= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005427#else
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005428 int native_ordering = byteorder >= 0;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005429#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005430 const char *encoding;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005431 Py_ssize_t nsize, pos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005432 PyObject *errorHandler = NULL;
5433 PyObject *exc = NULL;
5434 PyObject *rep = NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005435
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005436 if (!PyUnicode_Check(str)) {
5437 PyErr_BadArgument();
5438 return NULL;
5439 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005440 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005441 return NULL;
5442 kind = PyUnicode_KIND(str);
5443 data = PyUnicode_DATA(str);
5444 len = PyUnicode_GET_LENGTH(str);
5445
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005446 if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
Serhiy Storchaka30793282014-01-04 22:44:01 +02005447 return PyErr_NoMemory();
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005448 nsize = len + (byteorder == 0);
Mark Dickinsonc04ddff2012-10-06 18:04:49 +01005449 v = PyBytes_FromStringAndSize(NULL, nsize * 4);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005450 if (v == NULL)
5451 return NULL;
5452
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005453 /* output buffer is 4-bytes aligned */
5454 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005455 out = (uint32_t *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005456 if (byteorder == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005457 *out++ = 0xFEFF;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005458 if (len == 0)
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005459 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005460
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005461 if (byteorder == -1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005462 encoding = "utf-32-le";
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005463 else if (byteorder == 1)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005464 encoding = "utf-32-be";
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005465 else
5466 encoding = "utf-32";
5467
5468 if (kind == PyUnicode_1BYTE_KIND) {
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005469 ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5470 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005471 }
5472
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005473 pos = 0;
5474 while (pos < len) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005475 Py_ssize_t repsize, moreunits;
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005476
5477 if (kind == PyUnicode_2BYTE_KIND) {
5478 pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
5479 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005480 }
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005481 else {
5482 assert(kind == PyUnicode_4BYTE_KIND);
5483 pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
5484 &out, native_ordering);
5485 }
5486 if (pos == len)
5487 break;
Guido van Rossum98297ee2007-11-06 21:34:58 +00005488
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005489 rep = unicode_encode_call_errorhandler(
5490 errors, &errorHandler,
5491 encoding, "surrogates not allowed",
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005492 str, &exc, pos, pos + 1, &pos);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005493 if (!rep)
5494 goto error;
5495
5496 if (PyBytes_Check(rep)) {
5497 repsize = PyBytes_GET_SIZE(rep);
5498 if (repsize & 3) {
5499 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005500 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005501 "surrogates not allowed");
5502 goto error;
5503 }
5504 moreunits = repsize / 4;
5505 }
5506 else {
5507 assert(PyUnicode_Check(rep));
5508 if (PyUnicode_READY(rep) < 0)
5509 goto error;
5510 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5511 if (!PyUnicode_IS_ASCII(rep)) {
5512 raise_encode_exception(&exc, encoding,
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005513 str, pos - 1, pos,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005514 "surrogates not allowed");
5515 goto error;
5516 }
5517 }
5518
5519 /* four bytes are reserved for each surrogate */
5520 if (moreunits > 1) {
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005521 Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005522 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005523 /* integer overflow */
5524 PyErr_NoMemory();
5525 goto error;
5526 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005527 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005528 goto error;
Benjamin Peterson9b3d7702016-09-06 13:24:00 -07005529 out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005530 }
5531
5532 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005533 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005534 out += moreunits;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005535 } else /* rep is unicode */ {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005536 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005537 ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5538 &out, native_ordering);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005539 }
5540
5541 Py_CLEAR(rep);
5542 }
5543
5544 /* Cut back to size actually needed. This is necessary for, for example,
5545 encoding of a string containing isolated surrogates and the 'ignore'
5546 handler is used. */
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005547 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005548 if (nsize != PyBytes_GET_SIZE(v))
5549 _PyBytes_Resize(&v, nsize);
5550 Py_XDECREF(errorHandler);
5551 Py_XDECREF(exc);
Serhiy Storchaka0d4df752015-05-12 23:12:45 +03005552 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005553 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005554 error:
5555 Py_XDECREF(rep);
5556 Py_XDECREF(errorHandler);
5557 Py_XDECREF(exc);
5558 Py_XDECREF(v);
5559 return NULL;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005560}
5561
Alexander Belopolsky40018472011-02-26 01:02:56 +00005562PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005563PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5564 Py_ssize_t size,
5565 const char *errors,
5566 int byteorder)
5567{
5568 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005569 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005570 if (tmp == NULL)
5571 return NULL;
5572 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5573 Py_DECREF(tmp);
5574 return result;
5575}
5576
5577PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005578PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005579{
Victor Stinnerb960b342011-11-20 19:12:52 +01005580 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005581}
5582
Guido van Rossumd57fd912000-03-10 22:53:23 +00005583/* --- UTF-16 Codec ------------------------------------------------------- */
5584
Tim Peters772747b2001-08-09 22:21:55 +00005585PyObject *
5586PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005587 Py_ssize_t size,
5588 const char *errors,
5589 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005590{
Walter Dörwald69652032004-09-07 20:24:22 +00005591 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5592}
5593
5594PyObject *
5595PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005596 Py_ssize_t size,
5597 const char *errors,
5598 int *byteorder,
5599 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005600{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005601 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005602 Py_ssize_t startinpos;
5603 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005604 _PyUnicodeWriter writer;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005605 const unsigned char *q, *e;
Tim Peters772747b2001-08-09 22:21:55 +00005606 int bo = 0; /* assume native ordering by default */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005607 int native_ordering;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005608 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005609 PyObject *errorHandler = NULL;
5610 PyObject *exc = NULL;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005611 const char *encoding;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005612
Tim Peters772747b2001-08-09 22:21:55 +00005613 q = (unsigned char *)s;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005614 e = q + size;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615
5616 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005617 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005618
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005619 /* Check for BOM marks (U+FEFF) in the input and adjust current
5620 byte order setting accordingly. In native mode, the leading BOM
5621 mark is skipped, in all other modes, it is copied to the output
5622 stream as-is (giving a ZWNBSP character). */
Antoine Pitrou63065d72012-05-15 23:48:04 +02005623 if (bo == 0 && size >= 2) {
5624 const Py_UCS4 bom = (q[1] << 8) | q[0];
5625 if (bom == 0xFEFF) {
5626 q += 2;
5627 bo = -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00005628 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005629 else if (bom == 0xFFFE) {
5630 q += 2;
5631 bo = 1;
5632 }
5633 if (byteorder)
5634 *byteorder = bo;
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005635 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005636
Antoine Pitrou63065d72012-05-15 23:48:04 +02005637 if (q == e) {
5638 if (consumed)
5639 *consumed = size;
Serhiy Storchaka678db842013-01-26 12:16:36 +02005640 _Py_RETURN_UNICODE_EMPTY();
Tim Peters772747b2001-08-09 22:21:55 +00005641 }
Antoine Pitrou63065d72012-05-15 23:48:04 +02005642
Christian Heimes743e0cd2012-10-17 23:52:17 +02005643#if PY_LITTLE_ENDIAN
Antoine Pitrou63065d72012-05-15 23:48:04 +02005644 native_ordering = bo <= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005645 encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
Antoine Pitrouab868312009-01-10 15:40:25 +00005646#else
Antoine Pitrou63065d72012-05-15 23:48:04 +02005647 native_ordering = bo >= 0;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005648 encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
Antoine Pitrouab868312009-01-10 15:40:25 +00005649#endif
Tim Peters772747b2001-08-09 22:21:55 +00005650
Antoine Pitrou63065d72012-05-15 23:48:04 +02005651 /* Note: size will always be longer than the resulting Unicode
Xiang Zhang2c7fd462018-01-31 20:48:05 +08005652 character count normally. Error handler will take care of
5653 resizing when needed. */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005654 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02005655 writer.min_length = (e - q + 1) / 2;
5656 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005657 goto onError;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005658
Antoine Pitrou63065d72012-05-15 23:48:04 +02005659 while (1) {
5660 Py_UCS4 ch = 0;
5661 if (e - q >= 2) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005662 int kind = writer.kind;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005663 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005664 if (PyUnicode_IS_ASCII(writer.buffer))
Antoine Pitrou63065d72012-05-15 23:48:04 +02005665 ch = asciilib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005666 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005667 native_ordering);
5668 else
5669 ch = ucs1lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005670 (Py_UCS1*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005671 native_ordering);
5672 } else if (kind == PyUnicode_2BYTE_KIND) {
5673 ch = ucs2lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005674 (Py_UCS2*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005675 native_ordering);
5676 } else {
5677 assert(kind == PyUnicode_4BYTE_KIND);
5678 ch = ucs4lib_utf16_decode(&q, e,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005679 (Py_UCS4*)writer.data, &writer.pos,
Antoine Pitrou63065d72012-05-15 23:48:04 +02005680 native_ordering);
Antoine Pitrouab868312009-01-10 15:40:25 +00005681 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005682 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005683
Antoine Pitrou63065d72012-05-15 23:48:04 +02005684 switch (ch)
5685 {
5686 case 0:
5687 /* remaining byte at the end? (size should be even) */
5688 if (q == e || consumed)
5689 goto End;
5690 errmsg = "truncated data";
5691 startinpos = ((const char *)q) - starts;
5692 endinpos = ((const char *)e) - starts;
5693 break;
5694 /* The remaining input chars are ignored if the callback
5695 chooses to skip the input */
5696 case 1:
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005697 q -= 2;
5698 if (consumed)
Serhiy Storchakaae3b32a2013-01-08 23:40:52 +02005699 goto End;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005700 errmsg = "unexpected end of data";
Serhiy Storchaka48e188e2013-01-08 23:14:24 +02005701 startinpos = ((const char *)q) - starts;
Antoine Pitrou63065d72012-05-15 23:48:04 +02005702 endinpos = ((const char *)e) - starts;
5703 break;
5704 case 2:
5705 errmsg = "illegal encoding";
5706 startinpos = ((const char *)q) - 2 - starts;
5707 endinpos = startinpos + 2;
5708 break;
5709 case 3:
5710 errmsg = "illegal UTF-16 surrogate";
5711 startinpos = ((const char *)q) - 4 - starts;
5712 endinpos = startinpos + 2;
5713 break;
5714 default:
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02005715 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005716 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005717 continue;
5718 }
5719
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005720 if (unicode_decode_call_errorhandler_writer(
Antoine Pitrouab868312009-01-10 15:40:25 +00005721 errors,
5722 &errorHandler,
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005723 encoding, errmsg,
Antoine Pitrouab868312009-01-10 15:40:25 +00005724 &starts,
5725 (const char **)&e,
5726 &startinpos,
5727 &endinpos,
5728 &exc,
5729 (const char **)&q,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005730 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00005731 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 }
5733
Antoine Pitrou63065d72012-05-15 23:48:04 +02005734End:
Walter Dörwald69652032004-09-07 20:24:22 +00005735 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005736 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005737
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005738 Py_XDECREF(errorHandler);
5739 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005740 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005741
Benjamin Peterson29060642009-01-31 22:14:21 +00005742 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005743 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005744 Py_XDECREF(errorHandler);
5745 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005746 return NULL;
5747}
5748
Tim Peters772747b2001-08-09 22:21:55 +00005749PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005750_PyUnicode_EncodeUTF16(PyObject *str,
5751 const char *errors,
5752 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753{
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005754 enum PyUnicode_Kind kind;
5755 const void *data;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005756 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005757 PyObject *v;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005758 unsigned short *out;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005759 Py_ssize_t pairs;
Christian Heimes743e0cd2012-10-17 23:52:17 +02005760#if PY_BIG_ENDIAN
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005761 int native_ordering = byteorder >= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005762#else
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005763 int native_ordering = byteorder <= 0;
Tim Peters772747b2001-08-09 22:21:55 +00005764#endif
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005765 const char *encoding;
5766 Py_ssize_t nsize, pos;
5767 PyObject *errorHandler = NULL;
5768 PyObject *exc = NULL;
5769 PyObject *rep = NULL;
Tim Peters772747b2001-08-09 22:21:55 +00005770
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005771 if (!PyUnicode_Check(str)) {
5772 PyErr_BadArgument();
5773 return NULL;
5774 }
Benjamin Petersonbac79492012-01-14 13:34:47 -05005775 if (PyUnicode_READY(str) == -1)
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005776 return NULL;
5777 kind = PyUnicode_KIND(str);
5778 data = PyUnicode_DATA(str);
5779 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005780
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005781 pairs = 0;
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005782 if (kind == PyUnicode_4BYTE_KIND) {
5783 const Py_UCS4 *in = (const Py_UCS4 *)data;
5784 const Py_UCS4 *end = in + len;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005785 while (in < end) {
5786 if (*in++ >= 0x10000) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005787 pairs++;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005788 }
5789 }
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005790 }
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005791 if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005792 return PyErr_NoMemory();
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005793 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005794 nsize = len + pairs + (byteorder == 0);
5795 v = PyBytes_FromStringAndSize(NULL, nsize * 2);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005796 if (v == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005797 return NULL;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005798 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005799
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005800 /* output buffer is 2-bytes aligned */
Antoine Pitrouca8aa4a2012-09-20 20:56:47 +02005801 assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005802 out = (unsigned short *)PyBytes_AS_STRING(v);
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005803 if (byteorder == 0) {
Antoine Pitrou27f6a3b2012-06-15 22:15:23 +02005804 *out++ = 0xFEFF;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005805 }
5806 if (len == 0) {
Guido van Rossum98297ee2007-11-06 21:34:58 +00005807 goto done;
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005808 }
Tim Peters772747b2001-08-09 22:21:55 +00005809
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005810 if (kind == PyUnicode_1BYTE_KIND) {
5811 ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
5812 goto done;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005813 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005814
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005815 if (byteorder < 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005816 encoding = "utf-16-le";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005817 }
5818 else if (byteorder > 0) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005819 encoding = "utf-16-be";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005820 }
5821 else {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005822 encoding = "utf-16";
Victor Stinner1a05d6c2016-09-02 12:12:23 +02005823 }
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005824
5825 pos = 0;
5826 while (pos < len) {
5827 Py_ssize_t repsize, moreunits;
5828
5829 if (kind == PyUnicode_2BYTE_KIND) {
5830 pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
5831 &out, native_ordering);
5832 }
5833 else {
5834 assert(kind == PyUnicode_4BYTE_KIND);
5835 pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
5836 &out, native_ordering);
5837 }
5838 if (pos == len)
5839 break;
5840
5841 rep = unicode_encode_call_errorhandler(
5842 errors, &errorHandler,
5843 encoding, "surrogates not allowed",
5844 str, &exc, pos, pos + 1, &pos);
5845 if (!rep)
5846 goto error;
5847
5848 if (PyBytes_Check(rep)) {
5849 repsize = PyBytes_GET_SIZE(rep);
5850 if (repsize & 1) {
5851 raise_encode_exception(&exc, encoding,
5852 str, pos - 1, pos,
5853 "surrogates not allowed");
5854 goto error;
5855 }
5856 moreunits = repsize / 2;
5857 }
5858 else {
5859 assert(PyUnicode_Check(rep));
5860 if (PyUnicode_READY(rep) < 0)
5861 goto error;
5862 moreunits = repsize = PyUnicode_GET_LENGTH(rep);
5863 if (!PyUnicode_IS_ASCII(rep)) {
5864 raise_encode_exception(&exc, encoding,
5865 str, pos - 1, pos,
5866 "surrogates not allowed");
5867 goto error;
5868 }
5869 }
5870
5871 /* two bytes are reserved for each surrogate */
5872 if (moreunits > 1) {
5873 Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005874 if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005875 /* integer overflow */
5876 PyErr_NoMemory();
5877 goto error;
5878 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03005879 if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005880 goto error;
5881 out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
5882 }
5883
5884 if (PyBytes_Check(rep)) {
Christian Heimesf051e432016-09-13 20:22:02 +02005885 memcpy(out, PyBytes_AS_STRING(rep), repsize);
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005886 out += moreunits;
5887 } else /* rep is unicode */ {
5888 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
5889 ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
5890 &out, native_ordering);
5891 }
5892
5893 Py_CLEAR(rep);
5894 }
5895
5896 /* Cut back to size actually needed. This is necessary for, for example,
5897 encoding of a string containing isolated surrogates and the 'ignore' handler
5898 is used. */
5899 nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
5900 if (nsize != PyBytes_GET_SIZE(v))
5901 _PyBytes_Resize(&v, nsize);
5902 Py_XDECREF(errorHandler);
5903 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00005904 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005905 return v;
Serhiy Storchaka58cf6072013-11-19 11:32:41 +02005906 error:
5907 Py_XDECREF(rep);
5908 Py_XDECREF(errorHandler);
5909 Py_XDECREF(exc);
5910 Py_XDECREF(v);
5911 return NULL;
5912#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913}
5914
Alexander Belopolsky40018472011-02-26 01:02:56 +00005915PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005916PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5917 Py_ssize_t size,
5918 const char *errors,
5919 int byteorder)
5920{
5921 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02005922 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005923 if (tmp == NULL)
5924 return NULL;
5925 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5926 Py_DECREF(tmp);
5927 return result;
5928}
5929
5930PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005931PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005933 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005934}
5935
5936/* --- Unicode Escape Codec ----------------------------------------------- */
5937
Fredrik Lundh06d12682001-01-24 07:59:11 +00005938static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005939
Alexander Belopolsky40018472011-02-26 01:02:56 +00005940PyObject *
Eric V. Smith42454af2016-10-31 09:22:08 -04005941_PyUnicode_DecodeUnicodeEscape(const char *s,
5942 Py_ssize_t size,
5943 const char *errors,
5944 const char **first_invalid_escape)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005945{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005946 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01005947 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005948 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005949 PyObject *errorHandler = NULL;
5950 PyObject *exc = NULL;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005951
Eric V. Smith42454af2016-10-31 09:22:08 -04005952 // so we can remember if we've seen an invalid escape char or not
5953 *first_invalid_escape = NULL;
5954
Victor Stinner62ec3312016-09-06 17:04:34 -07005955 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02005956 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07005957 }
5958 /* Escaped strings will always be longer than the resulting
5959 Unicode string, so we start with size here and then reduce the
5960 length after conversion to the true value.
5961 (but if the error callback returns a long replacement string
5962 we'll have to allocate more space) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02005963 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07005964 writer.min_length = size;
5965 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
5966 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005967 }
5968
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969 end = s + size;
5970 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07005971 unsigned char c = (unsigned char) *s++;
5972 Py_UCS4 ch;
5973 int count;
5974 Py_ssize_t startinpos;
5975 Py_ssize_t endinpos;
5976 const char *message;
5977
5978#define WRITE_ASCII_CHAR(ch) \
5979 do { \
5980 assert(ch <= 127); \
5981 assert(writer.pos < writer.size); \
5982 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5983 } while(0)
5984
5985#define WRITE_CHAR(ch) \
5986 do { \
5987 if (ch <= writer.maxchar) { \
5988 assert(writer.pos < writer.size); \
5989 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
5990 } \
5991 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
5992 goto onError; \
5993 } \
5994 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005995
5996 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07005997 if (c != '\\') {
5998 WRITE_CHAR(c);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 continue;
6000 }
6001
Victor Stinner62ec3312016-09-06 17:04:34 -07006002 startinpos = s - starts - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003 /* \ - Escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006004 if (s >= end) {
6005 message = "\\ at end of string";
6006 goto error;
6007 }
6008 c = (unsigned char) *s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006009
Victor Stinner62ec3312016-09-06 17:04:34 -07006010 assert(writer.pos < writer.size);
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006011 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006012
Benjamin Peterson29060642009-01-31 22:14:21 +00006013 /* \x escapes */
Victor Stinner62ec3312016-09-06 17:04:34 -07006014 case '\n': continue;
6015 case '\\': WRITE_ASCII_CHAR('\\'); continue;
6016 case '\'': WRITE_ASCII_CHAR('\''); continue;
6017 case '\"': WRITE_ASCII_CHAR('\"'); continue;
6018 case 'b': WRITE_ASCII_CHAR('\b'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006019 /* FF */
Victor Stinner62ec3312016-09-06 17:04:34 -07006020 case 'f': WRITE_ASCII_CHAR('\014'); continue;
6021 case 't': WRITE_ASCII_CHAR('\t'); continue;
6022 case 'n': WRITE_ASCII_CHAR('\n'); continue;
6023 case 'r': WRITE_ASCII_CHAR('\r'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006024 /* VT */
Victor Stinner62ec3312016-09-06 17:04:34 -07006025 case 'v': WRITE_ASCII_CHAR('\013'); continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006026 /* BEL, not classic C */
Victor Stinner62ec3312016-09-06 17:04:34 -07006027 case 'a': WRITE_ASCII_CHAR('\007'); continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006028
Benjamin Peterson29060642009-01-31 22:14:21 +00006029 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006030 case '0': case '1': case '2': case '3':
6031 case '4': case '5': case '6': case '7':
Victor Stinner62ec3312016-09-06 17:04:34 -07006032 ch = c - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00006033 if (s < end && '0' <= *s && *s <= '7') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006034 ch = (ch<<3) + *s++ - '0';
6035 if (s < end && '0' <= *s && *s <= '7') {
6036 ch = (ch<<3) + *s++ - '0';
6037 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006038 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006039 WRITE_CHAR(ch);
6040 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006041
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 /* hex escapes */
6043 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006044 case 'x':
Victor Stinner62ec3312016-09-06 17:04:34 -07006045 count = 2;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006046 message = "truncated \\xXX escape";
6047 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006048
Benjamin Peterson29060642009-01-31 22:14:21 +00006049 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006050 case 'u':
Victor Stinner62ec3312016-09-06 17:04:34 -07006051 count = 4;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006052 message = "truncated \\uXXXX escape";
6053 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006054
Benjamin Peterson29060642009-01-31 22:14:21 +00006055 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00006056 case 'U':
Victor Stinner62ec3312016-09-06 17:04:34 -07006057 count = 8;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006058 message = "truncated \\UXXXXXXXX escape";
6059 hexescape:
Victor Stinner62ec3312016-09-06 17:04:34 -07006060 for (ch = 0; count && s < end; ++s, --count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006061 c = (unsigned char)*s;
Victor Stinner62ec3312016-09-06 17:04:34 -07006062 ch <<= 4;
6063 if (c >= '0' && c <= '9') {
6064 ch += c - '0';
6065 }
6066 else if (c >= 'a' && c <= 'f') {
6067 ch += c - ('a' - 10);
6068 }
6069 else if (c >= 'A' && c <= 'F') {
6070 ch += c - ('A' - 10);
6071 }
6072 else {
6073 break;
6074 }
Fredrik Lundhdf846752000-09-03 11:29:49 +00006075 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006076 if (count) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006077 goto error;
Victor Stinner62ec3312016-09-06 17:04:34 -07006078 }
6079
6080 /* when we get here, ch is a 32-bit unicode character */
6081 if (ch > MAX_UNICODE) {
6082 message = "illegal Unicode character";
6083 goto error;
6084 }
6085
6086 WRITE_CHAR(ch);
6087 continue;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006088
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006090 case 'N':
Fredrik Lundhccc74732001-02-18 22:13:49 +00006091 if (ucnhash_CAPI == NULL) {
6092 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006093 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
6094 PyUnicodeData_CAPSULE_NAME, 1);
Victor Stinner62ec3312016-09-06 17:04:34 -07006095 if (ucnhash_CAPI == NULL) {
6096 PyErr_SetString(
6097 PyExc_UnicodeError,
6098 "\\N escapes not supported (can't load unicodedata module)"
6099 );
6100 goto onError;
6101 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00006102 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006103
6104 message = "malformed \\N character escape";
Gregory P. Smith746b2d32018-11-13 13:16:54 -08006105 if (s < end && *s == '{') {
Victor Stinner62ec3312016-09-06 17:04:34 -07006106 const char *start = ++s;
6107 size_t namelen;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006108 /* look for the closing brace */
Victor Stinner62ec3312016-09-06 17:04:34 -07006109 while (s < end && *s != '}')
Fredrik Lundhccc74732001-02-18 22:13:49 +00006110 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006111 namelen = s - start;
6112 if (namelen && s < end) {
Fredrik Lundhccc74732001-02-18 22:13:49 +00006113 /* found a name. look it up in the unicode database */
Fredrik Lundhccc74732001-02-18 22:13:49 +00006114 s++;
Victor Stinner62ec3312016-09-06 17:04:34 -07006115 ch = 0xffffffff; /* in case 'getcode' messes up */
6116 if (namelen <= INT_MAX &&
6117 ucnhash_CAPI->getcode(NULL, start, (int)namelen,
6118 &ch, 0)) {
6119 assert(ch <= MAX_UNICODE);
6120 WRITE_CHAR(ch);
6121 continue;
6122 }
6123 message = "unknown Unicode character name";
Fredrik Lundhccc74732001-02-18 22:13:49 +00006124 }
6125 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006126 goto error;
Fredrik Lundhccc74732001-02-18 22:13:49 +00006127
6128 default:
Eric V. Smith42454af2016-10-31 09:22:08 -04006129 if (*first_invalid_escape == NULL) {
6130 *first_invalid_escape = s-1; /* Back up one char, since we've
6131 already incremented s. */
6132 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006133 WRITE_ASCII_CHAR('\\');
6134 WRITE_CHAR(c);
6135 continue;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136 }
Serhiy Storchakad6793772013-01-29 10:20:44 +02006137
6138 error:
6139 endinpos = s-starts;
Victor Stinner62ec3312016-09-06 17:04:34 -07006140 writer.min_length = end - s + writer.pos;
Serhiy Storchaka8fe5a9f2013-01-29 10:37:39 +02006141 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchakad6793772013-01-29 10:20:44 +02006142 errors, &errorHandler,
6143 "unicodeescape", message,
6144 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner62ec3312016-09-06 17:04:34 -07006145 &writer)) {
Serhiy Storchakad6793772013-01-29 10:20:44 +02006146 goto onError;
Victor Stinner62ec3312016-09-06 17:04:34 -07006147 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006148 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006149
6150#undef WRITE_ASCII_CHAR
6151#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006152 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006153
Walter Dörwaldd4ade082003-08-15 15:00:26 +00006154 Py_XDECREF(errorHandler);
6155 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006156 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwald8c077222002-03-25 11:16:18 +00006157
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006159 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006160 Py_XDECREF(errorHandler);
6161 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006162 return NULL;
6163}
6164
Eric V. Smith42454af2016-10-31 09:22:08 -04006165PyObject *
6166PyUnicode_DecodeUnicodeEscape(const char *s,
6167 Py_ssize_t size,
6168 const char *errors)
6169{
6170 const char *first_invalid_escape;
6171 PyObject *result = _PyUnicode_DecodeUnicodeEscape(s, size, errors,
6172 &first_invalid_escape);
6173 if (result == NULL)
6174 return NULL;
6175 if (first_invalid_escape != NULL) {
6176 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
6177 "invalid escape sequence '\\%c'",
Serhiy Storchaka56cb4652017-10-20 17:08:15 +03006178 (unsigned char)*first_invalid_escape) < 0) {
Eric V. Smith42454af2016-10-31 09:22:08 -04006179 Py_DECREF(result);
6180 return NULL;
6181 }
6182 }
6183 return result;
6184}
6185
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006186/* Return a Unicode-Escape string version of the Unicode object. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187
Alexander Belopolsky40018472011-02-26 01:02:56 +00006188PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006190{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006191 Py_ssize_t i, len;
Victor Stinner62ec3312016-09-06 17:04:34 -07006192 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006194 enum PyUnicode_Kind kind;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006195 void *data;
Victor Stinner62ec3312016-09-06 17:04:34 -07006196 Py_ssize_t expandsize;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197
Ezio Melottie7f90372012-10-05 03:33:31 +03006198 /* Initial allocation is based on the longest-possible character
Thomas Wouters89f507f2006-12-13 04:49:30 +00006199 escape.
6200
Ezio Melottie7f90372012-10-05 03:33:31 +03006201 For UCS1 strings it's '\xxx', 4 bytes per source character.
6202 For UCS2 strings it's '\uxxxx', 6 bytes per source character.
6203 For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
Thomas Wouters89f507f2006-12-13 04:49:30 +00006204 */
6205
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006206 if (!PyUnicode_Check(unicode)) {
6207 PyErr_BadArgument();
6208 return NULL;
6209 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006210 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006211 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006212 }
Victor Stinner358af132015-10-12 22:36:57 +02006213
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006214 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006215 if (len == 0) {
6216 return PyBytes_FromStringAndSize(NULL, 0);
6217 }
6218
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006219 kind = PyUnicode_KIND(unicode);
6220 data = PyUnicode_DATA(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006221 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6222 bytes, and 1 byte characters 4. */
6223 expandsize = kind * 2 + 2;
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006224 if (len > PY_SSIZE_T_MAX / expandsize) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006225 return PyErr_NoMemory();
6226 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006227 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Victor Stinner62ec3312016-09-06 17:04:34 -07006228 if (repr == NULL) {
6229 return NULL;
6230 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006231
Victor Stinner62ec3312016-09-06 17:04:34 -07006232 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006233 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01006234 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006235
Victor Stinner62ec3312016-09-06 17:04:34 -07006236 /* U+0000-U+00ff range */
6237 if (ch < 0x100) {
6238 if (ch >= ' ' && ch < 127) {
6239 if (ch != '\\') {
6240 /* Copy printable US ASCII as-is */
6241 *p++ = (char) ch;
6242 }
6243 /* Escape backslashes */
6244 else {
6245 *p++ = '\\';
6246 *p++ = '\\';
6247 }
6248 }
Victor Stinner358af132015-10-12 22:36:57 +02006249
Victor Stinner62ec3312016-09-06 17:04:34 -07006250 /* Map special whitespace to '\t', \n', '\r' */
6251 else if (ch == '\t') {
6252 *p++ = '\\';
6253 *p++ = 't';
6254 }
6255 else if (ch == '\n') {
6256 *p++ = '\\';
6257 *p++ = 'n';
6258 }
6259 else if (ch == '\r') {
6260 *p++ = '\\';
6261 *p++ = 'r';
6262 }
6263
6264 /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
6265 else {
6266 *p++ = '\\';
6267 *p++ = 'x';
6268 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6269 *p++ = Py_hexdigits[ch & 0x000F];
6270 }
Tim Petersced69f82003-09-16 20:30:58 +00006271 }
Serhiy Storchakaac0720e2016-11-21 11:46:51 +02006272 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006273 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006274 *p++ = '\\';
6275 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006276 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6277 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6278 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6279 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006280 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006281 /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
6282 else {
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006283
Victor Stinner62ec3312016-09-06 17:04:34 -07006284 /* Make sure that the first two digits are zero */
6285 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006286 *p++ = '\\';
Victor Stinner62ec3312016-09-06 17:04:34 -07006287 *p++ = 'U';
6288 *p++ = '0';
6289 *p++ = '0';
6290 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
6291 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
6292 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
6293 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
6294 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6295 *p++ = Py_hexdigits[ch & 0x0000000F];
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006296 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006297 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006298
Victor Stinner62ec3312016-09-06 17:04:34 -07006299 assert(p - PyBytes_AS_STRING(repr) > 0);
6300 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6301 return NULL;
6302 }
6303 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006304}
6305
Alexander Belopolsky40018472011-02-26 01:02:56 +00006306PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006307PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6308 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006309{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006310 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006311 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Victor Stinner62ec3312016-09-06 17:04:34 -07006312 if (tmp == NULL) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006313 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006314 }
6315
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006316 result = PyUnicode_AsUnicodeEscapeString(tmp);
6317 Py_DECREF(tmp);
6318 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006319}
6320
6321/* --- Raw Unicode Escape Codec ------------------------------------------- */
6322
Alexander Belopolsky40018472011-02-26 01:02:56 +00006323PyObject *
6324PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006325 Py_ssize_t size,
6326 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006327{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006328 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006329 _PyUnicodeWriter writer;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006330 const char *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006331 PyObject *errorHandler = NULL;
6332 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006333
Victor Stinner62ec3312016-09-06 17:04:34 -07006334 if (size == 0) {
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006335 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner62ec3312016-09-06 17:04:34 -07006336 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006337
Guido van Rossumd57fd912000-03-10 22:53:23 +00006338 /* Escaped strings will always be longer than the resulting
6339 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006340 length after conversion to the true value. (But decoding error
6341 handler might have to resize the string) */
Victor Stinner8f674cc2013-04-17 23:02:17 +02006342 _PyUnicodeWriter_Init(&writer);
Victor Stinner62ec3312016-09-06 17:04:34 -07006343 writer.min_length = size;
6344 if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
6345 goto onError;
6346 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006347
Guido van Rossumd57fd912000-03-10 22:53:23 +00006348 end = s + size;
6349 while (s < end) {
Victor Stinner62ec3312016-09-06 17:04:34 -07006350 unsigned char c = (unsigned char) *s++;
6351 Py_UCS4 ch;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006352 int count;
Victor Stinner62ec3312016-09-06 17:04:34 -07006353 Py_ssize_t startinpos;
6354 Py_ssize_t endinpos;
6355 const char *message;
6356
6357#define WRITE_CHAR(ch) \
6358 do { \
6359 if (ch <= writer.maxchar) { \
6360 assert(writer.pos < writer.size); \
6361 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
6362 } \
6363 else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
6364 goto onError; \
6365 } \
6366 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006367
Benjamin Peterson29060642009-01-31 22:14:21 +00006368 /* Non-escape characters are interpreted as Unicode ordinals */
Victor Stinner62ec3312016-09-06 17:04:34 -07006369 if (c != '\\' || s >= end) {
6370 WRITE_CHAR(c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006371 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006372 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006373
Victor Stinner62ec3312016-09-06 17:04:34 -07006374 c = (unsigned char) *s++;
6375 if (c == 'u') {
6376 count = 4;
6377 message = "truncated \\uXXXX escape";
Benjamin Peterson29060642009-01-31 22:14:21 +00006378 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006379 else if (c == 'U') {
6380 count = 8;
6381 message = "truncated \\UXXXXXXXX escape";
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006382 }
6383 else {
Victor Stinner62ec3312016-09-06 17:04:34 -07006384 assert(writer.pos < writer.size);
6385 PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
6386 WRITE_CHAR(c);
6387 continue;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006388 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006389 startinpos = s - starts - 2;
6390
6391 /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
6392 for (ch = 0; count && s < end; ++s, --count) {
6393 c = (unsigned char)*s;
6394 ch <<= 4;
6395 if (c >= '0' && c <= '9') {
6396 ch += c - '0';
6397 }
6398 else if (c >= 'a' && c <= 'f') {
6399 ch += c - ('a' - 10);
6400 }
6401 else if (c >= 'A' && c <= 'F') {
6402 ch += c - ('A' - 10);
6403 }
6404 else {
6405 break;
6406 }
6407 }
6408 if (!count) {
6409 if (ch <= MAX_UNICODE) {
6410 WRITE_CHAR(ch);
6411 continue;
6412 }
6413 message = "\\Uxxxxxxxx out of range";
6414 }
6415
6416 endinpos = s-starts;
6417 writer.min_length = end - s + writer.pos;
6418 if (unicode_decode_call_errorhandler_writer(
6419 errors, &errorHandler,
6420 "rawunicodeescape", message,
6421 &starts, &end, &startinpos, &endinpos, &exc, &s,
6422 &writer)) {
6423 goto onError;
6424 }
Serhiy Storchakab7e2d672018-02-13 08:27:33 +02006425 assert(end - s <= writer.size - writer.pos);
Victor Stinner62ec3312016-09-06 17:04:34 -07006426
6427#undef WRITE_CHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00006428 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006429 Py_XDECREF(errorHandler);
6430 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006431 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00006432
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006434 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006435 Py_XDECREF(errorHandler);
6436 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006437 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006438
Guido van Rossumd57fd912000-03-10 22:53:23 +00006439}
6440
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006441
Alexander Belopolsky40018472011-02-26 01:02:56 +00006442PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006443PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006444{
Victor Stinner62ec3312016-09-06 17:04:34 -07006445 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006446 char *p;
Victor Stinner62ec3312016-09-06 17:04:34 -07006447 Py_ssize_t expandsize, pos;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006448 int kind;
6449 void *data;
6450 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006451
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006452 if (!PyUnicode_Check(unicode)) {
6453 PyErr_BadArgument();
6454 return NULL;
6455 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006456 if (PyUnicode_READY(unicode) == -1) {
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006457 return NULL;
Victor Stinner62ec3312016-09-06 17:04:34 -07006458 }
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006459 kind = PyUnicode_KIND(unicode);
6460 data = PyUnicode_DATA(unicode);
6461 len = PyUnicode_GET_LENGTH(unicode);
Victor Stinner62ec3312016-09-06 17:04:34 -07006462 if (kind == PyUnicode_1BYTE_KIND) {
6463 return PyBytes_FromStringAndSize(data, len);
6464 }
Victor Stinner0e368262011-11-10 20:12:49 +01006465
Victor Stinner62ec3312016-09-06 17:04:34 -07006466 /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
6467 bytes, and 1 byte characters 4. */
6468 expandsize = kind * 2 + 2;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006469
Victor Stinner62ec3312016-09-06 17:04:34 -07006470 if (len > PY_SSIZE_T_MAX / expandsize) {
6471 return PyErr_NoMemory();
6472 }
6473 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
6474 if (repr == NULL) {
6475 return NULL;
6476 }
6477 if (len == 0) {
6478 return repr;
6479 }
6480
6481 p = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006482 for (pos = 0; pos < len; pos++) {
6483 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Victor Stinner358af132015-10-12 22:36:57 +02006484
Victor Stinner62ec3312016-09-06 17:04:34 -07006485 /* U+0000-U+00ff range: Copy 8-bit characters as-is */
6486 if (ch < 0x100) {
6487 *p++ = (char) ch;
Tim Petersced69f82003-09-16 20:30:58 +00006488 }
Xiang Zhang2b77a922018-02-13 18:33:32 +08006489 /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
Victor Stinner62ec3312016-09-06 17:04:34 -07006490 else if (ch < 0x10000) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006491 *p++ = '\\';
6492 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006493 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6494 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6495 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6496 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006497 }
Victor Stinner62ec3312016-09-06 17:04:34 -07006498 /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
6499 else {
6500 assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
6501 *p++ = '\\';
6502 *p++ = 'U';
6503 *p++ = '0';
6504 *p++ = '0';
6505 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6506 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6507 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6508 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6509 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6510 *p++ = Py_hexdigits[ch & 15];
6511 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006512 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006513
Victor Stinner62ec3312016-09-06 17:04:34 -07006514 assert(p > PyBytes_AS_STRING(repr));
6515 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
6516 return NULL;
6517 }
6518 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006519}
6520
Alexander Belopolsky40018472011-02-26 01:02:56 +00006521PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006522PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6523 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006524{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006525 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006526 PyObject *tmp = PyUnicode_FromWideChar(s, size);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006527 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006528 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006529 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6530 Py_DECREF(tmp);
6531 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006532}
6533
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006534/* --- Unicode Internal Codec ------------------------------------------- */
6535
Alexander Belopolsky40018472011-02-26 01:02:56 +00006536PyObject *
6537_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006538 Py_ssize_t size,
6539 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006540{
6541 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006542 Py_ssize_t startinpos;
6543 Py_ssize_t endinpos;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006544 _PyUnicodeWriter writer;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006545 const char *end;
6546 const char *reason;
6547 PyObject *errorHandler = NULL;
6548 PyObject *exc = NULL;
6549
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006550 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006551 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006552 1))
6553 return NULL;
6554
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03006555 if (size < 0) {
6556 PyErr_BadInternalCall();
6557 return NULL;
6558 }
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02006559 if (size == 0)
6560 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006561
Victor Stinner8f674cc2013-04-17 23:02:17 +02006562 _PyUnicodeWriter_Init(&writer);
6563 if (size / Py_UNICODE_SIZE > PY_SSIZE_T_MAX - 1) {
6564 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00006565 goto onError;
Victor Stinner8f674cc2013-04-17 23:02:17 +02006566 }
6567 writer.min_length = (size + (Py_UNICODE_SIZE - 1)) / Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006568
Victor Stinner8f674cc2013-04-17 23:02:17 +02006569 end = s + size;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006570 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006571 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006572 Py_UCS4 ch;
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006573 if (end - s < Py_UNICODE_SIZE) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006574 endinpos = end-starts;
6575 reason = "truncated input";
6576 goto error;
6577 }
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006578 /* We copy the raw representation one byte at a time because the
6579 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006580 ((char *) &uch)[0] = s[0];
6581 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006582#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006583 ((char *) &uch)[2] = s[2];
6584 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006585#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006586 ch = uch;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006587#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006588 /* We have to sanity check the raw data, otherwise doom looms for
6589 some malformed UCS-4 data. */
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006590 if (ch > 0x10ffff) {
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006591 endinpos = s - starts + Py_UNICODE_SIZE;
6592 reason = "illegal code point (> 0x10FFFF)";
6593 goto error;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006594 }
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006595#endif
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006596 s += Py_UNICODE_SIZE;
6597#ifndef Py_UNICODE_WIDE
Serhiy Storchaka03ee12e2013-02-07 16:25:25 +02006598 if (Py_UNICODE_IS_HIGH_SURROGATE(ch) && end - s >= Py_UNICODE_SIZE)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006599 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006600 Py_UNICODE uch2;
6601 ((char *) &uch2)[0] = s[0];
6602 ((char *) &uch2)[1] = s[1];
Victor Stinner551ac952011-11-29 22:58:13 +01006603 if (Py_UNICODE_IS_LOW_SURROGATE(uch2))
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006604 {
Victor Stinner551ac952011-11-29 22:58:13 +01006605 ch = Py_UNICODE_JOIN_SURROGATES(uch, uch2);
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006606 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006607 }
6608 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006609#endif
6610
Victor Stinner8a1a6cf2013-04-14 02:35:33 +02006611 if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006612 goto onError;
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006613 continue;
6614
6615 error:
6616 startinpos = s - starts;
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006617 if (unicode_decode_call_errorhandler_writer(
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006618 errors, &errorHandler,
6619 "unicode_internal", reason,
6620 &starts, &end, &startinpos, &endinpos, &exc, &s,
Serhiy Storchakad0c79dc2013-02-07 16:26:55 +02006621 &writer))
Serhiy Storchaka3fd4ab32013-02-07 16:23:21 +02006622 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006623 }
6624
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006625 Py_XDECREF(errorHandler);
6626 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006627 return _PyUnicodeWriter_Finish(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006628
Benjamin Peterson29060642009-01-31 22:14:21 +00006629 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006630 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006631 Py_XDECREF(errorHandler);
6632 Py_XDECREF(exc);
6633 return NULL;
6634}
6635
Guido van Rossumd57fd912000-03-10 22:53:23 +00006636/* --- Latin-1 Codec ------------------------------------------------------ */
6637
Alexander Belopolsky40018472011-02-26 01:02:56 +00006638PyObject *
6639PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006640 Py_ssize_t size,
6641 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006642{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006643 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006644 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006645}
6646
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006647/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006648static void
6649make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006650 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006651 PyObject *unicode,
6652 Py_ssize_t startpos, Py_ssize_t endpos,
6653 const char *reason)
6654{
6655 if (*exceptionObject == NULL) {
6656 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006657 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006658 encoding, unicode, startpos, endpos, reason);
6659 }
6660 else {
6661 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6662 goto onError;
6663 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6664 goto onError;
6665 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6666 goto onError;
6667 return;
6668 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02006669 Py_CLEAR(*exceptionObject);
Martin v. Löwis9e816682011-11-02 12:45:42 +01006670 }
6671}
6672
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006673/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006674static void
6675raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006676 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006677 PyObject *unicode,
6678 Py_ssize_t startpos, Py_ssize_t endpos,
6679 const char *reason)
6680{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006681 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006682 encoding, unicode, startpos, endpos, reason);
6683 if (*exceptionObject != NULL)
6684 PyCodec_StrictErrors(*exceptionObject);
6685}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006686
6687/* error handling callback helper:
6688 build arguments, call the callback and check the arguments,
6689 put the result into newpos and return the replacement string, which
6690 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006691static PyObject *
6692unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006693 PyObject **errorHandler,
6694 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006695 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006696 Py_ssize_t startpos, Py_ssize_t endpos,
6697 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006698{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +02006699 static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006700 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006701 PyObject *restuple;
6702 PyObject *resunicode;
6703
6704 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006706 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006708 }
6709
Benjamin Petersonbac79492012-01-14 13:34:47 -05006710 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006711 return NULL;
6712 len = PyUnicode_GET_LENGTH(unicode);
6713
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006714 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006715 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006716 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006717 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01006719 restuple = PyObject_CallFunctionObjArgs(
6720 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006721 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006722 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006723 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006724 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 Py_DECREF(restuple);
6726 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006727 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006728 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006729 &resunicode, newpos)) {
6730 Py_DECREF(restuple);
6731 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006732 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006733 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6734 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6735 Py_DECREF(restuple);
6736 return NULL;
6737 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006738 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006739 *newpos = len + *newpos;
6740 if (*newpos<0 || *newpos>len) {
Victor Stinnera33bce02014-07-04 22:47:46 +02006741 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 Py_DECREF(restuple);
6743 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006744 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006745 Py_INCREF(resunicode);
6746 Py_DECREF(restuple);
6747 return resunicode;
6748}
6749
Alexander Belopolsky40018472011-02-26 01:02:56 +00006750static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006751unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006752 const char *errors,
Victor Stinner0030cd52015-09-24 14:45:00 +02006753 const Py_UCS4 limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006755 /* input state */
6756 Py_ssize_t pos=0, size;
6757 int kind;
6758 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006759 /* pointer into the output */
6760 char *str;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006761 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6762 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Victor Stinner50149202015-09-22 00:26:54 +02006763 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006764 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02006765 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006766 PyObject *rep = NULL;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006767 /* output object */
6768 _PyBytesWriter writer;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006769
Benjamin Petersonbac79492012-01-14 13:34:47 -05006770 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006771 return NULL;
6772 size = PyUnicode_GET_LENGTH(unicode);
6773 kind = PyUnicode_KIND(unicode);
6774 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006775 /* allocate enough for a simple encoding without
6776 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006777 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006778 return PyBytes_FromStringAndSize(NULL, 0);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006779
6780 _PyBytesWriter_Init(&writer);
6781 str = _PyBytesWriter_Alloc(&writer, size);
6782 if (str == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006783 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006784
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006785 while (pos < size) {
Victor Stinner0030cd52015-09-24 14:45:00 +02006786 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006787
Benjamin Peterson29060642009-01-31 22:14:21 +00006788 /* can we encode this? */
Victor Stinner0030cd52015-09-24 14:45:00 +02006789 if (ch < limit) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006790 /* no overflow check, because we know that the space is enough */
Victor Stinner0030cd52015-09-24 14:45:00 +02006791 *str++ = (char)ch;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006792 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006793 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006794 else {
Victor Stinner6bd525b2015-10-09 13:10:05 +02006795 Py_ssize_t newpos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006796 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006797 Py_ssize_t collstart = pos;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006798 Py_ssize_t collend = collstart + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006799 /* find all unecodable characters */
Victor Stinner50149202015-09-22 00:26:54 +02006800
Benjamin Petersona1c1be42014-09-29 18:18:57 -04006801 while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006802 ++collend;
Victor Stinner50149202015-09-22 00:26:54 +02006803
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006804 /* Only overallocate the buffer if it's not the last write */
6805 writer.overallocate = (collend < size);
6806
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02006808 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02006809 error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02006810
6811 switch (error_handler) {
6812 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006813 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006814 goto onError;
Victor Stinner50149202015-09-22 00:26:54 +02006815
6816 case _Py_ERROR_REPLACE:
Victor Stinner01ada392015-10-01 21:54:51 +02006817 memset(str, '?', collend - collstart);
6818 str += (collend - collstart);
Stefan Krahf432a322017-08-21 13:09:59 +02006819 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02006820 case _Py_ERROR_IGNORE:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006821 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006822 break;
Victor Stinner50149202015-09-22 00:26:54 +02006823
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006824 case _Py_ERROR_BACKSLASHREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006825 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006826 writer.min_size -= (collend - collstart);
6827 str = backslashreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006828 unicode, collstart, collend);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006829 if (str == NULL)
6830 goto onError;
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006831 pos = collend;
6832 break;
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006833
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006834 case _Py_ERROR_XMLCHARREFREPLACE:
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006835 /* subtract preallocated bytes */
Victor Stinnerad771582015-10-09 12:38:53 +02006836 writer.min_size -= (collend - collstart);
6837 str = xmlcharrefreplace(&writer, str,
Victor Stinnere7bf86c2015-10-09 01:39:28 +02006838 unicode, collstart, collend);
6839 if (str == NULL)
6840 goto onError;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006841 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006842 break;
Victor Stinner50149202015-09-22 00:26:54 +02006843
Victor Stinnerc3713e92015-09-29 12:32:13 +02006844 case _Py_ERROR_SURROGATEESCAPE:
6845 for (i = collstart; i < collend; ++i) {
6846 ch = PyUnicode_READ(kind, data, i);
6847 if (ch < 0xdc80 || 0xdcff < ch) {
6848 /* Not a UTF-8b surrogate */
6849 break;
6850 }
6851 *str++ = (char)(ch - 0xdc00);
6852 ++pos;
6853 }
6854 if (i >= collend)
6855 break;
6856 collstart = pos;
6857 assert(collstart != collend);
Stefan Krahf432a322017-08-21 13:09:59 +02006858 /* fall through */
Victor Stinnerc3713e92015-09-29 12:32:13 +02006859
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 default:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006861 rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
6862 encoding, reason, unicode, &exc,
6863 collstart, collend, &newpos);
6864 if (rep == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006865 goto onError;
Victor Stinner0030cd52015-09-24 14:45:00 +02006866
Raymond Hettinger15f44ab2016-08-30 10:47:49 -07006867 /* subtract preallocated bytes */
Xiang Zhangd04d8472016-11-23 19:34:01 +08006868 writer.min_size -= newpos - collstart;
Victor Stinnerad771582015-10-09 12:38:53 +02006869
Victor Stinner6bd525b2015-10-09 13:10:05 +02006870 if (PyBytes_Check(rep)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00006871 /* Directly copy bytes result to output. */
Victor Stinnerce179bf2015-10-09 12:57:22 +02006872 str = _PyBytesWriter_WriteBytes(&writer, str,
Victor Stinner6bd525b2015-10-09 13:10:05 +02006873 PyBytes_AS_STRING(rep),
6874 PyBytes_GET_SIZE(rep));
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006875 }
Victor Stinner6bd525b2015-10-09 13:10:05 +02006876 else {
6877 assert(PyUnicode_Check(rep));
Victor Stinner0030cd52015-09-24 14:45:00 +02006878
Victor Stinner6bd525b2015-10-09 13:10:05 +02006879 if (PyUnicode_READY(rep) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006880 goto onError;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006881
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006882 if (limit == 256 ?
6883 PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
6884 !PyUnicode_IS_ASCII(rep))
6885 {
6886 /* Not all characters are smaller than limit */
6887 raise_encode_exception(&exc, encoding, unicode,
6888 collstart, collend, reason);
6889 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006890 }
Serhiy Storchaka99250d52016-11-23 15:13:00 +02006891 assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
6892 str = _PyBytesWriter_WriteBytes(&writer, str,
6893 PyUnicode_DATA(rep),
6894 PyUnicode_GET_LENGTH(rep));
Benjamin Peterson29060642009-01-31 22:14:21 +00006895 }
Alexey Izbyshev74a307d2018-08-19 21:52:04 +03006896 if (str == NULL)
6897 goto onError;
6898
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006899 pos = newpos;
Victor Stinner6bd525b2015-10-09 13:10:05 +02006900 Py_CLEAR(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006901 }
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006902
6903 /* If overallocation was disabled, ensure that it was the last
6904 write. Otherwise, we missed an optimization */
6905 assert(writer.overallocate || pos == size);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006906 }
6907 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006908
Victor Stinner50149202015-09-22 00:26:54 +02006909 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006910 Py_XDECREF(exc);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006911 return _PyBytesWriter_Finish(&writer, str);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006912
6913 onError:
Victor Stinner6bd525b2015-10-09 13:10:05 +02006914 Py_XDECREF(rep);
Victor Stinnerfdfbf782015-10-09 00:33:49 +02006915 _PyBytesWriter_Dealloc(&writer);
Victor Stinner50149202015-09-22 00:26:54 +02006916 Py_XDECREF(error_handler_obj);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006917 Py_XDECREF(exc);
6918 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006919}
6920
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006921/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006922PyObject *
6923PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006924 Py_ssize_t size,
6925 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006926{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006927 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02006928 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006929 if (unicode == NULL)
6930 return NULL;
6931 result = unicode_encode_ucs1(unicode, errors, 256);
6932 Py_DECREF(unicode);
6933 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006934}
6935
Alexander Belopolsky40018472011-02-26 01:02:56 +00006936PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006937_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006938{
6939 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006940 PyErr_BadArgument();
6941 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006943 if (PyUnicode_READY(unicode) == -1)
6944 return NULL;
6945 /* Fast path: if it is a one-byte string, construct
6946 bytes object directly. */
6947 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6948 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6949 PyUnicode_GET_LENGTH(unicode));
6950 /* Non-Latin-1 characters present. Defer to above function to
6951 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006952 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006953}
6954
6955PyObject*
6956PyUnicode_AsLatin1String(PyObject *unicode)
6957{
6958 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006959}
6960
6961/* --- 7-bit ASCII Codec -------------------------------------------------- */
6962
Alexander Belopolsky40018472011-02-26 01:02:56 +00006963PyObject *
6964PyUnicode_DecodeASCII(const char *s,
6965 Py_ssize_t size,
6966 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006967{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006968 const char *starts = s;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006969 _PyUnicodeWriter writer;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006970 int kind;
6971 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006972 Py_ssize_t startinpos;
6973 Py_ssize_t endinpos;
6974 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006975 const char *e;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006976 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006977 PyObject *exc = NULL;
Victor Stinnerf96418d2015-09-21 23:06:27 +02006978 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Tim Petersced69f82003-09-16 20:30:58 +00006979
Guido van Rossumd57fd912000-03-10 22:53:23 +00006980 if (size == 0)
Serhiy Storchaka678db842013-01-26 12:16:36 +02006981 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01006982
Guido van Rossumd57fd912000-03-10 22:53:23 +00006983 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006984 if (size == 1 && (unsigned char)s[0] < 128)
6985 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006986
Victor Stinner8f674cc2013-04-17 23:02:17 +02006987 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02006988 writer.min_length = size;
6989 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) < 0)
Victor Stinner8f674cc2013-04-17 23:02:17 +02006990 return NULL;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006991
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006992 e = s + size;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006993 data = writer.data;
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006994 outpos = ascii_decode(s, e, (Py_UCS1 *)data);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006995 writer.pos = outpos;
6996 if (writer.pos == size)
6997 return _PyUnicodeWriter_Finish(&writer);
Antoine Pitrouca5f91b2012-05-10 16:36:02 +02006998
Victor Stinnerfc009ef2012-11-07 00:36:38 +01006999 s += writer.pos;
7000 kind = writer.kind;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007001 while (s < e) {
Antoine Pitrou9ed5f272013-08-13 20:18:52 +02007002 unsigned char c = (unsigned char)*s;
Benjamin Peterson29060642009-01-31 22:14:21 +00007003 if (c < 128) {
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007004 PyUnicode_WRITE(kind, data, writer.pos, c);
7005 writer.pos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00007006 ++s;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007007 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +00007008 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007009
7010 /* byte outsize range 0x00..0x7f: call the error handler */
7011
7012 if (error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02007013 error_handler = _Py_GetErrorHandler(errors);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007014
7015 switch (error_handler)
7016 {
7017 case _Py_ERROR_REPLACE:
7018 case _Py_ERROR_SURROGATEESCAPE:
7019 /* Fast-path: the error handler only writes one character,
Victor Stinnerca9381e2015-09-22 00:58:32 +02007020 but we may switch to UCS2 at the first write */
7021 if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
7022 goto onError;
7023 kind = writer.kind;
7024 data = writer.data;
Victor Stinnerf96418d2015-09-21 23:06:27 +02007025
7026 if (error_handler == _Py_ERROR_REPLACE)
7027 PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
7028 else
7029 PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
7030 writer.pos++;
7031 ++s;
7032 break;
7033
7034 case _Py_ERROR_IGNORE:
7035 ++s;
7036 break;
7037
7038 default:
Benjamin Peterson29060642009-01-31 22:14:21 +00007039 startinpos = s-starts;
7040 endinpos = startinpos + 1;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007041 if (unicode_decode_call_errorhandler_writer(
Victor Stinnerf96418d2015-09-21 23:06:27 +02007042 errors, &error_handler_obj,
Benjamin Peterson29060642009-01-31 22:14:21 +00007043 "ascii", "ordinal not in range(128)",
7044 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007045 &writer))
Benjamin Peterson29060642009-01-31 22:14:21 +00007046 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007047 kind = writer.kind;
7048 data = writer.data;
Benjamin Peterson29060642009-01-31 22:14:21 +00007049 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007050 }
Victor Stinnerf96418d2015-09-21 23:06:27 +02007051 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007052 Py_XDECREF(exc);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007053 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00007054
Benjamin Peterson29060642009-01-31 22:14:21 +00007055 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007056 _PyUnicodeWriter_Dealloc(&writer);
Victor Stinnerf96418d2015-09-21 23:06:27 +02007057 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007058 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007059 return NULL;
7060}
7061
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007062/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007063PyObject *
7064PyUnicode_EncodeASCII(const Py_UNICODE *p,
7065 Py_ssize_t size,
7066 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007067{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007068 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007069 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007070 if (unicode == NULL)
7071 return NULL;
7072 result = unicode_encode_ucs1(unicode, errors, 128);
7073 Py_DECREF(unicode);
7074 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007075}
7076
Alexander Belopolsky40018472011-02-26 01:02:56 +00007077PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007078_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007079{
7080 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007081 PyErr_BadArgument();
7082 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007083 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007084 if (PyUnicode_READY(unicode) == -1)
7085 return NULL;
7086 /* Fast path: if it is an ASCII-only string, construct bytes object
7087 directly. Else defer to above function to raise the exception. */
Victor Stinneraf037572013-04-14 18:44:10 +02007088 if (PyUnicode_IS_ASCII(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007089 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
7090 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01007091 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007092}
7093
7094PyObject *
7095PyUnicode_AsASCIIString(PyObject *unicode)
7096{
7097 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007098}
7099
Steve Dowercc16be82016-09-08 10:35:16 -07007100#ifdef MS_WINDOWS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007101
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007102/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007103
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00007104#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007105#define NEED_RETRY
7106#endif
7107
Victor Stinner3a50e702011-10-18 21:21:00 +02007108#ifndef WC_ERR_INVALID_CHARS
7109# define WC_ERR_INVALID_CHARS 0x0080
7110#endif
7111
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007112static const char*
Victor Stinner3a50e702011-10-18 21:21:00 +02007113code_page_name(UINT code_page, PyObject **obj)
7114{
7115 *obj = NULL;
7116 if (code_page == CP_ACP)
7117 return "mbcs";
7118 if (code_page == CP_UTF7)
7119 return "CP_UTF7";
7120 if (code_page == CP_UTF8)
7121 return "CP_UTF8";
7122
7123 *obj = PyBytes_FromFormat("cp%u", code_page);
7124 if (*obj == NULL)
7125 return NULL;
7126 return PyBytes_AS_STRING(*obj);
7127}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007128
Victor Stinner3a50e702011-10-18 21:21:00 +02007129static DWORD
7130decode_code_page_flags(UINT code_page)
7131{
7132 if (code_page == CP_UTF7) {
7133 /* The CP_UTF7 decoder only supports flags=0 */
7134 return 0;
7135 }
7136 else
7137 return MB_ERR_INVALID_CHARS;
7138}
7139
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007140/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007141 * Decode a byte string from a Windows code page into unicode object in strict
7142 * mode.
7143 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007144 * Returns consumed size if succeed, returns -2 on decode error, or raise an
7145 * OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007146 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007147static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007148decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007149 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007150 const char *in,
7151 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007152{
Victor Stinner3a50e702011-10-18 21:21:00 +02007153 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01007154 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007155 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007156
7157 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007158 assert(insize > 0);
7159 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7160 if (outsize <= 0)
7161 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007162
7163 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007164 /* Create unicode object */
Victor Stinnerab595942011-12-17 04:59:06 +01007165 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007166 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007167 if (*v == NULL)
7168 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007169 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007170 }
7171 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007172 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007173 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner16e6a802011-12-12 13:24:15 +01007174 if (unicode_resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007175 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007177 }
7178
7179 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7181 if (outsize <= 0)
7182 goto error;
7183 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007184
Victor Stinner3a50e702011-10-18 21:21:00 +02007185error:
7186 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7187 return -2;
7188 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007189 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007190}
7191
Victor Stinner3a50e702011-10-18 21:21:00 +02007192/*
7193 * Decode a byte string from a code page into unicode object with an error
7194 * handler.
7195 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007196 * Returns consumed size if succeed, or raise an OSError or
Victor Stinner3a50e702011-10-18 21:21:00 +02007197 * UnicodeDecodeError exception and returns -1 on error.
7198 */
7199static int
7200decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007201 PyObject **v,
7202 const char *in, const int size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007203 const char *errors, int final)
Victor Stinner3a50e702011-10-18 21:21:00 +02007204{
7205 const char *startin = in;
7206 const char *endin = in + size;
7207 const DWORD flags = decode_code_page_flags(code_page);
7208 /* Ideally, we should get reason from FormatMessage. This is the Windows
7209 2000 English version of the message. */
7210 const char *reason = "No mapping for the Unicode character exists "
7211 "in the target code page.";
7212 /* each step cannot decode more than 1 character, but a character can be
7213 represented as a surrogate pair */
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007214 wchar_t buffer[2], *out;
Victor Stinner9f067f42013-06-05 00:21:31 +02007215 int insize;
7216 Py_ssize_t outsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 PyObject *errorHandler = NULL;
7218 PyObject *exc = NULL;
7219 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007220 const char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007221 DWORD err;
7222 int ret = -1;
7223
7224 assert(size > 0);
7225
7226 encoding = code_page_name(code_page, &encoding_obj);
7227 if (encoding == NULL)
7228 return -1;
7229
Victor Stinner7d00cc12014-03-17 23:08:06 +01007230 if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7232 UnicodeDecodeError. */
7233 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7234 if (exc != NULL) {
7235 PyCodec_StrictErrors(exc);
7236 Py_CLEAR(exc);
7237 }
7238 goto error;
7239 }
7240
7241 if (*v == NULL) {
7242 /* Create unicode object */
7243 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7244 PyErr_NoMemory();
7245 goto error;
7246 }
Victor Stinnerab595942011-12-17 04:59:06 +01007247 /* FIXME: don't use _PyUnicode_New(), but allocate a wchar_t* buffer */
Victor Stinner76a31a62011-11-04 00:05:13 +01007248 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007249 if (*v == NULL)
7250 goto error;
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007251 out = PyUnicode_AS_UNICODE(*v);
Victor Stinner3a50e702011-10-18 21:21:00 +02007252 }
7253 else {
7254 /* Extend unicode object */
7255 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7256 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7257 PyErr_NoMemory();
7258 goto error;
7259 }
Victor Stinner16e6a802011-12-12 13:24:15 +01007260 if (unicode_resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007261 goto error;
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007262 out = PyUnicode_AS_UNICODE(*v) + n;
Victor Stinner3a50e702011-10-18 21:21:00 +02007263 }
7264
7265 /* Decode the byte string character per character */
Victor Stinner3a50e702011-10-18 21:21:00 +02007266 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 */
Serhiy Storchaka4013c172018-12-03 10:36:45 +02007320 outsize = out - PyUnicode_AS_UNICODE(*v);
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 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);
Victor Stinner163403a2018-11-27 12:41:17 +010010120 void *data = PyUnicode_DATA(unicode);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010121 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
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013951 {"format", (PyCFunction)(void(*)(void)) 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