blob: bc98c44c740755ad6faed30629b7b37bbd1b5559 [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 */
7214 wchar_t buffer[2], *startout, *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;
7251 startout = PyUnicode_AS_UNICODE(*v);
7252 }
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;
7262 startout = PyUnicode_AS_UNICODE(*v) + n;
7263 }
7264
7265 /* Decode the byte string character per character */
7266 out = startout;
7267 while (in < endin)
7268 {
7269 /* Decode a character */
7270 insize = 1;
7271 do
7272 {
7273 outsize = MultiByteToWideChar(code_page, flags,
7274 in, insize,
7275 buffer, Py_ARRAY_LENGTH(buffer));
7276 if (outsize > 0)
7277 break;
7278 err = GetLastError();
7279 if (err != ERROR_NO_UNICODE_TRANSLATION
7280 && err != ERROR_INSUFFICIENT_BUFFER)
7281 {
7282 PyErr_SetFromWindowsErr(0);
7283 goto error;
7284 }
7285 insize++;
7286 }
7287 /* 4=maximum length of a UTF-8 sequence */
7288 while (insize <= 4 && (in + insize) <= endin);
7289
7290 if (outsize <= 0) {
7291 Py_ssize_t startinpos, endinpos, outpos;
7292
Victor Stinner7d00cc12014-03-17 23:08:06 +01007293 /* last character in partial decode? */
7294 if (in + insize >= endin && !final)
7295 break;
7296
Victor Stinner3a50e702011-10-18 21:21:00 +02007297 startinpos = in - startin;
7298 endinpos = startinpos + 1;
7299 outpos = out - PyUnicode_AS_UNICODE(*v);
Victor Stinnerfc009ef2012-11-07 00:36:38 +01007300 if (unicode_decode_call_errorhandler_wchar(
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 errors, &errorHandler,
7302 encoding, reason,
7303 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007304 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 {
7306 goto error;
7307 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007308 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007309 }
7310 else {
7311 in += insize;
7312 memcpy(out, buffer, outsize * sizeof(wchar_t));
7313 out += outsize;
7314 }
7315 }
7316
7317 /* write a NUL character at the end */
7318 *out = 0;
7319
7320 /* Extend unicode object */
7321 outsize = out - startout;
7322 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner16e6a802011-12-12 13:24:15 +01007323 if (unicode_resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007324 goto error;
Victor Stinnere1f17c62014-07-25 14:03:03 +02007325 /* (in - startin) <= size and size is an int */
7326 ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
Victor Stinner3a50e702011-10-18 21:21:00 +02007327
7328error:
7329 Py_XDECREF(encoding_obj);
7330 Py_XDECREF(errorHandler);
7331 Py_XDECREF(exc);
7332 return ret;
7333}
7334
Victor Stinner3a50e702011-10-18 21:21:00 +02007335static PyObject *
7336decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007337 const char *s, Py_ssize_t size,
7338 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007339{
Victor Stinner76a31a62011-11-04 00:05:13 +01007340 PyObject *v = NULL;
7341 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007342
Victor Stinner3a50e702011-10-18 21:21:00 +02007343 if (code_page < 0) {
7344 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7345 return NULL;
7346 }
Serhiy Storchaka64e461b2017-07-11 06:55:25 +03007347 if (size < 0) {
7348 PyErr_BadInternalCall();
7349 return NULL;
7350 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007351
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007352 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007353 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007354
Victor Stinner76a31a62011-11-04 00:05:13 +01007355 do
7356 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007357#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007358 if (size > INT_MAX) {
7359 chunk_size = INT_MAX;
7360 final = 0;
7361 done = 0;
7362 }
7363 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007364#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007365 {
7366 chunk_size = (int)size;
7367 final = (consumed == NULL);
7368 done = 1;
7369 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007370
Victor Stinner76a31a62011-11-04 00:05:13 +01007371 if (chunk_size == 0 && done) {
7372 if (v != NULL)
7373 break;
Serhiy Storchaka678db842013-01-26 12:16:36 +02007374 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner76a31a62011-11-04 00:05:13 +01007375 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007376
Victor Stinner76a31a62011-11-04 00:05:13 +01007377 converted = decode_code_page_strict(code_page, &v,
7378 s, chunk_size);
7379 if (converted == -2)
7380 converted = decode_code_page_errors(code_page, &v,
7381 s, chunk_size,
Victor Stinner7d00cc12014-03-17 23:08:06 +01007382 errors, final);
7383 assert(converted != 0 || done);
Victor Stinner76a31a62011-11-04 00:05:13 +01007384
7385 if (converted < 0) {
7386 Py_XDECREF(v);
7387 return NULL;
7388 }
7389
7390 if (consumed)
7391 *consumed += converted;
7392
7393 s += converted;
7394 size -= converted;
7395 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007396
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01007397 return unicode_result(v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007398}
7399
Alexander Belopolsky40018472011-02-26 01:02:56 +00007400PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007401PyUnicode_DecodeCodePageStateful(int code_page,
7402 const char *s,
7403 Py_ssize_t size,
7404 const char *errors,
7405 Py_ssize_t *consumed)
7406{
7407 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7408}
7409
7410PyObject *
7411PyUnicode_DecodeMBCSStateful(const char *s,
7412 Py_ssize_t size,
7413 const char *errors,
7414 Py_ssize_t *consumed)
7415{
7416 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7417}
7418
7419PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007420PyUnicode_DecodeMBCS(const char *s,
7421 Py_ssize_t size,
7422 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007423{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007424 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7425}
7426
Victor Stinner3a50e702011-10-18 21:21:00 +02007427static DWORD
7428encode_code_page_flags(UINT code_page, const char *errors)
7429{
7430 if (code_page == CP_UTF8) {
Steve Dower3e96f322015-03-02 08:01:10 -08007431 return WC_ERR_INVALID_CHARS;
Victor Stinner3a50e702011-10-18 21:21:00 +02007432 }
7433 else if (code_page == CP_UTF7) {
7434 /* CP_UTF7 only supports flags=0 */
7435 return 0;
7436 }
7437 else {
7438 if (errors != NULL && strcmp(errors, "replace") == 0)
7439 return 0;
7440 else
7441 return WC_NO_BEST_FIT_CHARS;
7442 }
7443}
7444
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007445/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007446 * Encode a Unicode string to a Windows code page into a byte string in strict
7447 * mode.
7448 *
7449 * Returns consumed characters if succeed, returns -2 on encode error, or raise
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007450 * an OSError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007451 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007452static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007453encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007454 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007455 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007456{
Victor Stinner554f3f02010-06-16 23:33:54 +00007457 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007458 BOOL *pusedDefaultChar = &usedDefaultChar;
7459 int outsize;
Victor Stinner24729f32011-11-10 20:31:37 +01007460 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007461 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007462 const DWORD flags = encode_code_page_flags(code_page, NULL);
7463 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007464 /* Create a substring so that we can get the UTF-16 representation
7465 of just the slice under consideration. */
7466 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007467
Martin v. Löwis3d325192011-11-04 18:23:06 +01007468 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007469
Victor Stinner3a50e702011-10-18 21:21:00 +02007470 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007471 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007472 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007473 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007474
Victor Stinner2fc507f2011-11-04 20:06:39 +01007475 substring = PyUnicode_Substring(unicode, offset, offset+len);
7476 if (substring == NULL)
7477 return -1;
7478 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7479 if (p == NULL) {
7480 Py_DECREF(substring);
7481 return -1;
7482 }
Victor Stinner9f067f42013-06-05 00:21:31 +02007483 assert(size <= INT_MAX);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007484
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007485 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007486 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007487 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007488 NULL, 0,
7489 NULL, pusedDefaultChar);
7490 if (outsize <= 0)
7491 goto error;
7492 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007493 if (pusedDefaultChar && *pusedDefaultChar) {
7494 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007495 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007496 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007497
Victor Stinner3a50e702011-10-18 21:21:00 +02007498 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007499 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007501 if (*outbytes == NULL) {
7502 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007503 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007504 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007506 }
7507 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007508 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007509 const Py_ssize_t n = PyBytes_Size(*outbytes);
7510 if (outsize > PY_SSIZE_T_MAX - n) {
7511 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007512 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007513 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007514 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007515 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7516 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007517 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007518 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007519 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007520 }
7521
7522 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007523 outsize = WideCharToMultiByte(code_page, flags,
Victor Stinner9f067f42013-06-05 00:21:31 +02007524 p, (int)size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007525 out, outsize,
7526 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007527 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007528 if (outsize <= 0)
7529 goto error;
7530 if (pusedDefaultChar && *pusedDefaultChar)
7531 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007532 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007533
Victor Stinner3a50e702011-10-18 21:21:00 +02007534error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007535 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007536 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7537 return -2;
7538 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007539 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007540}
7541
Victor Stinner3a50e702011-10-18 21:21:00 +02007542/*
Serhiy Storchakad65c9492015-11-02 14:10:23 +02007543 * Encode a Unicode string to a Windows code page into a byte string using an
Victor Stinner3a50e702011-10-18 21:21:00 +02007544 * error handler.
7545 *
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02007546 * Returns consumed characters if succeed, or raise an OSError and returns
Victor Stinner3a50e702011-10-18 21:21:00 +02007547 * -1 on other error.
7548 */
7549static int
7550encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007551 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007552 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007553{
Victor Stinner3a50e702011-10-18 21:21:00 +02007554 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007555 Py_ssize_t pos = unicode_offset;
7556 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007557 /* Ideally, we should get reason from FormatMessage. This is the Windows
7558 2000 English version of the message. */
7559 const char *reason = "invalid character";
7560 /* 4=maximum length of a UTF-8 sequence */
7561 char buffer[4];
7562 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7563 Py_ssize_t outsize;
7564 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007565 PyObject *errorHandler = NULL;
7566 PyObject *exc = NULL;
7567 PyObject *encoding_obj = NULL;
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02007568 const char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007569 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007570 PyObject *rep;
7571 int ret = -1;
7572
7573 assert(insize > 0);
7574
7575 encoding = code_page_name(code_page, &encoding_obj);
7576 if (encoding == NULL)
7577 return -1;
7578
7579 if (errors == NULL || strcmp(errors, "strict") == 0) {
7580 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7581 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007582 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007583 if (exc != NULL) {
7584 PyCodec_StrictErrors(exc);
7585 Py_DECREF(exc);
7586 }
7587 Py_XDECREF(encoding_obj);
7588 return -1;
7589 }
7590
7591 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7592 pusedDefaultChar = &usedDefaultChar;
7593 else
7594 pusedDefaultChar = NULL;
7595
7596 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7597 PyErr_NoMemory();
7598 goto error;
7599 }
7600 outsize = insize * Py_ARRAY_LENGTH(buffer);
7601
7602 if (*outbytes == NULL) {
7603 /* Create string object */
7604 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7605 if (*outbytes == NULL)
7606 goto error;
7607 out = PyBytes_AS_STRING(*outbytes);
7608 }
7609 else {
7610 /* Extend string object */
7611 Py_ssize_t n = PyBytes_Size(*outbytes);
7612 if (n > PY_SSIZE_T_MAX - outsize) {
7613 PyErr_NoMemory();
7614 goto error;
7615 }
7616 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7617 goto error;
7618 out = PyBytes_AS_STRING(*outbytes) + n;
7619 }
7620
7621 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007622 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007623 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007624 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7625 wchar_t chars[2];
7626 int charsize;
7627 if (ch < 0x10000) {
7628 chars[0] = (wchar_t)ch;
7629 charsize = 1;
7630 }
7631 else {
Victor Stinner76df43d2012-10-30 01:42:39 +01007632 chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
7633 chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007634 charsize = 2;
7635 }
7636
Victor Stinner3a50e702011-10-18 21:21:00 +02007637 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007638 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007639 buffer, Py_ARRAY_LENGTH(buffer),
7640 NULL, pusedDefaultChar);
7641 if (outsize > 0) {
7642 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7643 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007644 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007645 memcpy(out, buffer, outsize);
7646 out += outsize;
7647 continue;
7648 }
7649 }
7650 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7651 PyErr_SetFromWindowsErr(0);
7652 goto error;
7653 }
7654
Victor Stinner3a50e702011-10-18 21:21:00 +02007655 rep = unicode_encode_call_errorhandler(
7656 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007657 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007658 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007659 if (rep == NULL)
7660 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007661 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007662
7663 if (PyBytes_Check(rep)) {
7664 outsize = PyBytes_GET_SIZE(rep);
7665 if (outsize != 1) {
7666 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7667 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7668 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7669 Py_DECREF(rep);
7670 goto error;
7671 }
7672 out = PyBytes_AS_STRING(*outbytes) + offset;
7673 }
7674 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7675 out += outsize;
7676 }
7677 else {
7678 Py_ssize_t i;
7679 enum PyUnicode_Kind kind;
7680 void *data;
7681
Benjamin Petersonbac79492012-01-14 13:34:47 -05007682 if (PyUnicode_READY(rep) == -1) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007683 Py_DECREF(rep);
7684 goto error;
7685 }
7686
7687 outsize = PyUnicode_GET_LENGTH(rep);
7688 if (outsize != 1) {
7689 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7690 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7691 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7692 Py_DECREF(rep);
7693 goto error;
7694 }
7695 out = PyBytes_AS_STRING(*outbytes) + offset;
7696 }
7697 kind = PyUnicode_KIND(rep);
7698 data = PyUnicode_DATA(rep);
7699 for (i=0; i < outsize; i++) {
7700 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7701 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007702 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007703 encoding, unicode,
7704 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007705 "unable to encode error handler result to ASCII");
7706 Py_DECREF(rep);
7707 goto error;
7708 }
7709 *out = (unsigned char)ch;
7710 out++;
7711 }
7712 }
7713 Py_DECREF(rep);
7714 }
7715 /* write a NUL byte */
7716 *out = 0;
7717 outsize = out - PyBytes_AS_STRING(*outbytes);
7718 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7719 if (_PyBytes_Resize(outbytes, outsize) < 0)
7720 goto error;
7721 ret = 0;
7722
7723error:
7724 Py_XDECREF(encoding_obj);
7725 Py_XDECREF(errorHandler);
7726 Py_XDECREF(exc);
7727 return ret;
7728}
7729
Victor Stinner3a50e702011-10-18 21:21:00 +02007730static PyObject *
7731encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007732 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007733 const char *errors)
7734{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007735 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007736 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007737 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007738 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007739
Victor Stinner29dacf22015-01-26 16:41:32 +01007740 if (!PyUnicode_Check(unicode)) {
7741 PyErr_BadArgument();
7742 return NULL;
7743 }
7744
Benjamin Petersonbac79492012-01-14 13:34:47 -05007745 if (PyUnicode_READY(unicode) == -1)
Victor Stinner2fc507f2011-11-04 20:06:39 +01007746 return NULL;
7747 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007748
Victor Stinner3a50e702011-10-18 21:21:00 +02007749 if (code_page < 0) {
7750 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7751 return NULL;
7752 }
7753
Martin v. Löwis3d325192011-11-04 18:23:06 +01007754 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007755 return PyBytes_FromStringAndSize(NULL, 0);
7756
Victor Stinner7581cef2011-11-03 22:32:33 +01007757 offset = 0;
7758 do
7759 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007760#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007761 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007762 chunks. */
7763 if (len > INT_MAX/2) {
7764 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007765 done = 0;
7766 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007767 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007768#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007769 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007770 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007771 done = 1;
7772 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007773
Victor Stinner76a31a62011-11-04 00:05:13 +01007774 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007775 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007776 errors);
7777 if (ret == -2)
7778 ret = encode_code_page_errors(code_page, &outbytes,
7779 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007780 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007781 if (ret < 0) {
7782 Py_XDECREF(outbytes);
7783 return NULL;
7784 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007785
Victor Stinner7581cef2011-11-03 22:32:33 +01007786 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007787 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007788 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007789
Victor Stinner3a50e702011-10-18 21:21:00 +02007790 return outbytes;
7791}
7792
7793PyObject *
7794PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7795 Py_ssize_t size,
7796 const char *errors)
7797{
Victor Stinner7581cef2011-11-03 22:32:33 +01007798 PyObject *unicode, *res;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02007799 unicode = PyUnicode_FromWideChar(p, size);
Victor Stinner7581cef2011-11-03 22:32:33 +01007800 if (unicode == NULL)
7801 return NULL;
7802 res = encode_code_page(CP_ACP, unicode, errors);
7803 Py_DECREF(unicode);
7804 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007805}
7806
7807PyObject *
7808PyUnicode_EncodeCodePage(int code_page,
7809 PyObject *unicode,
7810 const char *errors)
7811{
Victor Stinner7581cef2011-11-03 22:32:33 +01007812 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007813}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007814
Alexander Belopolsky40018472011-02-26 01:02:56 +00007815PyObject *
7816PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007817{
Victor Stinner7581cef2011-11-03 22:32:33 +01007818 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007819}
7820
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007821#undef NEED_RETRY
7822
Steve Dowercc16be82016-09-08 10:35:16 -07007823#endif /* MS_WINDOWS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007824
Guido van Rossumd57fd912000-03-10 22:53:23 +00007825/* --- Character Mapping Codec -------------------------------------------- */
7826
Victor Stinnerfb161b12013-04-18 01:44:27 +02007827static int
7828charmap_decode_string(const char *s,
7829 Py_ssize_t size,
7830 PyObject *mapping,
7831 const char *errors,
7832 _PyUnicodeWriter *writer)
7833{
7834 const char *starts = s;
7835 const char *e;
7836 Py_ssize_t startinpos, endinpos;
7837 PyObject *errorHandler = NULL, *exc = NULL;
7838 Py_ssize_t maplen;
7839 enum PyUnicode_Kind mapkind;
7840 void *mapdata;
7841 Py_UCS4 x;
7842 unsigned char ch;
7843
7844 if (PyUnicode_READY(mapping) == -1)
7845 return -1;
7846
7847 maplen = PyUnicode_GET_LENGTH(mapping);
7848 mapdata = PyUnicode_DATA(mapping);
7849 mapkind = PyUnicode_KIND(mapping);
7850
7851 e = s + size;
7852
7853 if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
7854 /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
7855 * is disabled in encoding aliases, latin1 is preferred because
7856 * its implementation is faster. */
7857 Py_UCS1 *mapdata_ucs1 = (Py_UCS1 *)mapdata;
7858 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7859 Py_UCS4 maxchar = writer->maxchar;
7860
7861 assert (writer->kind == PyUnicode_1BYTE_KIND);
7862 while (s < e) {
7863 ch = *s;
7864 x = mapdata_ucs1[ch];
7865 if (x > maxchar) {
7866 if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
7867 goto onError;
7868 maxchar = writer->maxchar;
7869 outdata = (Py_UCS1 *)writer->data;
7870 }
7871 outdata[writer->pos] = x;
7872 writer->pos++;
7873 ++s;
7874 }
7875 return 0;
7876 }
7877
7878 while (s < e) {
7879 if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
7880 enum PyUnicode_Kind outkind = writer->kind;
7881 Py_UCS2 *mapdata_ucs2 = (Py_UCS2 *)mapdata;
7882 if (outkind == PyUnicode_1BYTE_KIND) {
7883 Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
7884 Py_UCS4 maxchar = writer->maxchar;
7885 while (s < e) {
7886 ch = *s;
7887 x = mapdata_ucs2[ch];
7888 if (x > maxchar)
7889 goto Error;
7890 outdata[writer->pos] = x;
7891 writer->pos++;
7892 ++s;
7893 }
7894 break;
7895 }
7896 else if (outkind == PyUnicode_2BYTE_KIND) {
7897 Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
7898 while (s < e) {
7899 ch = *s;
7900 x = mapdata_ucs2[ch];
7901 if (x == 0xFFFE)
7902 goto Error;
7903 outdata[writer->pos] = x;
7904 writer->pos++;
7905 ++s;
7906 }
7907 break;
7908 }
7909 }
7910 ch = *s;
7911
7912 if (ch < maplen)
7913 x = PyUnicode_READ(mapkind, mapdata, ch);
7914 else
7915 x = 0xfffe; /* invalid value */
7916Error:
7917 if (x == 0xfffe)
7918 {
7919 /* undefined mapping */
7920 startinpos = s-starts;
7921 endinpos = startinpos+1;
7922 if (unicode_decode_call_errorhandler_writer(
7923 errors, &errorHandler,
7924 "charmap", "character maps to <undefined>",
7925 &starts, &e, &startinpos, &endinpos, &exc, &s,
7926 writer)) {
7927 goto onError;
7928 }
7929 continue;
7930 }
7931
7932 if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
7933 goto onError;
7934 ++s;
7935 }
7936 Py_XDECREF(errorHandler);
7937 Py_XDECREF(exc);
7938 return 0;
7939
7940onError:
7941 Py_XDECREF(errorHandler);
7942 Py_XDECREF(exc);
7943 return -1;
7944}
7945
7946static int
7947charmap_decode_mapping(const char *s,
7948 Py_ssize_t size,
7949 PyObject *mapping,
7950 const char *errors,
7951 _PyUnicodeWriter *writer)
7952{
7953 const char *starts = s;
7954 const char *e;
7955 Py_ssize_t startinpos, endinpos;
7956 PyObject *errorHandler = NULL, *exc = NULL;
7957 unsigned char ch;
Victor Stinnerf4f24242013-05-07 01:01:31 +02007958 PyObject *key, *item = NULL;
Victor Stinnerfb161b12013-04-18 01:44:27 +02007959
7960 e = s + size;
7961
7962 while (s < e) {
7963 ch = *s;
7964
7965 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7966 key = PyLong_FromLong((long)ch);
7967 if (key == NULL)
7968 goto onError;
7969
7970 item = PyObject_GetItem(mapping, key);
7971 Py_DECREF(key);
7972 if (item == NULL) {
7973 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7974 /* No mapping found means: mapping is undefined. */
7975 PyErr_Clear();
7976 goto Undefined;
7977 } else
7978 goto onError;
7979 }
7980
7981 /* Apply mapping */
7982 if (item == Py_None)
7983 goto Undefined;
7984 if (PyLong_Check(item)) {
7985 long value = PyLong_AS_LONG(item);
7986 if (value == 0xFFFE)
7987 goto Undefined;
7988 if (value < 0 || value > MAX_UNICODE) {
7989 PyErr_Format(PyExc_TypeError,
7990 "character mapping must be in range(0x%lx)",
7991 (unsigned long)MAX_UNICODE + 1);
7992 goto onError;
7993 }
7994
7995 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
7996 goto onError;
7997 }
7998 else if (PyUnicode_Check(item)) {
7999 if (PyUnicode_READY(item) == -1)
8000 goto onError;
8001 if (PyUnicode_GET_LENGTH(item) == 1) {
8002 Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
8003 if (value == 0xFFFE)
8004 goto Undefined;
8005 if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
8006 goto onError;
8007 }
8008 else {
8009 writer->overallocate = 1;
8010 if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
8011 goto onError;
8012 }
8013 }
8014 else {
8015 /* wrong return value */
8016 PyErr_SetString(PyExc_TypeError,
8017 "character mapping must return integer, None or str");
8018 goto onError;
8019 }
8020 Py_CLEAR(item);
8021 ++s;
8022 continue;
8023
8024Undefined:
8025 /* undefined mapping */
8026 Py_CLEAR(item);
8027 startinpos = s-starts;
8028 endinpos = startinpos+1;
8029 if (unicode_decode_call_errorhandler_writer(
8030 errors, &errorHandler,
8031 "charmap", "character maps to <undefined>",
8032 &starts, &e, &startinpos, &endinpos, &exc, &s,
8033 writer)) {
8034 goto onError;
8035 }
8036 }
8037 Py_XDECREF(errorHandler);
8038 Py_XDECREF(exc);
8039 return 0;
8040
8041onError:
8042 Py_XDECREF(item);
8043 Py_XDECREF(errorHandler);
8044 Py_XDECREF(exc);
8045 return -1;
8046}
8047
Alexander Belopolsky40018472011-02-26 01:02:56 +00008048PyObject *
8049PyUnicode_DecodeCharmap(const char *s,
8050 Py_ssize_t size,
8051 PyObject *mapping,
8052 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008053{
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008054 _PyUnicodeWriter writer;
Tim Petersced69f82003-09-16 20:30:58 +00008055
Guido van Rossumd57fd912000-03-10 22:53:23 +00008056 /* Default to Latin-1 */
8057 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008058 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008059
Guido van Rossumd57fd912000-03-10 22:53:23 +00008060 if (size == 0)
Serhiy Storchakaed3c4122013-01-26 12:18:17 +02008061 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner8f674cc2013-04-17 23:02:17 +02008062 _PyUnicodeWriter_Init(&writer);
Victor Stinner170ca6f2013-04-18 00:25:28 +02008063 writer.min_length = size;
8064 if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008065 goto onError;
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008066
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008067 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008068 if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
8069 goto onError;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00008070 }
8071 else {
Victor Stinnerfb161b12013-04-18 01:44:27 +02008072 if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
8073 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008074 }
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008075 return _PyUnicodeWriter_Finish(&writer);
Tim Petersced69f82003-09-16 20:30:58 +00008076
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 onError:
Victor Stinnerfc009ef2012-11-07 00:36:38 +01008078 _PyUnicodeWriter_Dealloc(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008079 return NULL;
8080}
8081
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008082/* Charmap encoding: the lookup table */
8083
Alexander Belopolsky40018472011-02-26 01:02:56 +00008084struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00008085 PyObject_HEAD
8086 unsigned char level1[32];
8087 int count2, count3;
8088 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089};
8090
8091static PyObject*
8092encoding_map_size(PyObject *obj, PyObject* args)
8093{
8094 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008095 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00008096 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008097}
8098
8099static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008100 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 PyDoc_STR("Return the size (in bytes) of this object") },
8102 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008103};
8104
8105static void
8106encoding_map_dealloc(PyObject* o)
8107{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008108 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008109}
8110
8111static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008112 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008113 "EncodingMap", /*tp_name*/
8114 sizeof(struct encoding_map), /*tp_basicsize*/
8115 0, /*tp_itemsize*/
8116 /* methods */
8117 encoding_map_dealloc, /*tp_dealloc*/
8118 0, /*tp_print*/
8119 0, /*tp_getattr*/
8120 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00008121 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 0, /*tp_repr*/
8123 0, /*tp_as_number*/
8124 0, /*tp_as_sequence*/
8125 0, /*tp_as_mapping*/
8126 0, /*tp_hash*/
8127 0, /*tp_call*/
8128 0, /*tp_str*/
8129 0, /*tp_getattro*/
8130 0, /*tp_setattro*/
8131 0, /*tp_as_buffer*/
8132 Py_TPFLAGS_DEFAULT, /*tp_flags*/
8133 0, /*tp_doc*/
8134 0, /*tp_traverse*/
8135 0, /*tp_clear*/
8136 0, /*tp_richcompare*/
8137 0, /*tp_weaklistoffset*/
8138 0, /*tp_iter*/
8139 0, /*tp_iternext*/
8140 encoding_map_methods, /*tp_methods*/
8141 0, /*tp_members*/
8142 0, /*tp_getset*/
8143 0, /*tp_base*/
8144 0, /*tp_dict*/
8145 0, /*tp_descr_get*/
8146 0, /*tp_descr_set*/
8147 0, /*tp_dictoffset*/
8148 0, /*tp_init*/
8149 0, /*tp_alloc*/
8150 0, /*tp_new*/
8151 0, /*tp_free*/
8152 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008153};
8154
8155PyObject*
8156PyUnicode_BuildEncodingMap(PyObject* string)
8157{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008158 PyObject *result;
8159 struct encoding_map *mresult;
8160 int i;
8161 int need_dict = 0;
8162 unsigned char level1[32];
8163 unsigned char level2[512];
8164 unsigned char *mlevel1, *mlevel2, *mlevel3;
8165 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008166 int kind;
8167 void *data;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008168 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008169 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008170
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008171 if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008172 PyErr_BadArgument();
8173 return NULL;
8174 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008175 kind = PyUnicode_KIND(string);
8176 data = PyUnicode_DATA(string);
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008177 length = PyUnicode_GET_LENGTH(string);
8178 length = Py_MIN(length, 256);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008179 memset(level1, 0xFF, sizeof level1);
8180 memset(level2, 0xFF, sizeof level2);
8181
8182 /* If there isn't a one-to-one mapping of NULL to \0,
8183 or if there are non-BMP characters, we need to use
8184 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008185 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008186 need_dict = 1;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008187 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008188 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008189 ch = PyUnicode_READ(kind, data, i);
8190 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008191 need_dict = 1;
8192 break;
8193 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008194 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008195 /* unmapped character */
8196 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008197 l1 = ch >> 11;
8198 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008199 if (level1[l1] == 0xFF)
8200 level1[l1] = count2++;
8201 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00008202 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008203 }
8204
8205 if (count2 >= 0xFF || count3 >= 0xFF)
8206 need_dict = 1;
8207
8208 if (need_dict) {
8209 PyObject *result = PyDict_New();
8210 PyObject *key, *value;
8211 if (!result)
8212 return NULL;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008213 for (i = 0; i < length; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008214 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008215 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008216 if (!key || !value)
8217 goto failed1;
8218 if (PyDict_SetItem(result, key, value) == -1)
8219 goto failed1;
8220 Py_DECREF(key);
8221 Py_DECREF(value);
8222 }
8223 return result;
8224 failed1:
8225 Py_XDECREF(key);
8226 Py_XDECREF(value);
8227 Py_DECREF(result);
8228 return NULL;
8229 }
8230
8231 /* Create a three-level trie */
8232 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8233 16*count2 + 128*count3 - 1);
8234 if (!result)
8235 return PyErr_NoMemory();
8236 PyObject_Init(result, &EncodingMapType);
8237 mresult = (struct encoding_map*)result;
8238 mresult->count2 = count2;
8239 mresult->count3 = count3;
8240 mlevel1 = mresult->level1;
8241 mlevel2 = mresult->level23;
8242 mlevel3 = mresult->level23 + 16*count2;
8243 memcpy(mlevel1, level1, 32);
8244 memset(mlevel2, 0xFF, 16*count2);
8245 memset(mlevel3, 0, 128*count3);
8246 count3 = 0;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008247 for (i = 1; i < length; i++) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008248 int o1, o2, o3, i2, i3;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008249 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
8250 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008251 /* unmapped character */
8252 continue;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008253 o1 = ch>>11;
8254 o2 = (ch>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008255 i2 = 16*mlevel1[o1] + o2;
8256 if (mlevel2[i2] == 0xFF)
8257 mlevel2[i2] = count3++;
Antoine Pitrouaaefac72012-06-16 22:48:21 +02008258 o3 = ch & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008259 i3 = 128*mlevel2[i2] + o3;
8260 mlevel3[i3] = i;
8261 }
8262 return result;
8263}
8264
8265static int
Victor Stinner22168992011-11-20 17:09:18 +01008266encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008267{
8268 struct encoding_map *map = (struct encoding_map*)mapping;
8269 int l1 = c>>11;
8270 int l2 = (c>>7) & 0xF;
8271 int l3 = c & 0x7F;
8272 int i;
8273
Victor Stinner22168992011-11-20 17:09:18 +01008274 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008276 if (c == 0)
8277 return 0;
8278 /* level 1*/
8279 i = map->level1[l1];
8280 if (i == 0xFF) {
8281 return -1;
8282 }
8283 /* level 2*/
8284 i = map->level23[16*i+l2];
8285 if (i == 0xFF) {
8286 return -1;
8287 }
8288 /* level 3 */
8289 i = map->level23[16*map->count2 + 128*i + l3];
8290 if (i == 0) {
8291 return -1;
8292 }
8293 return i;
8294}
8295
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008296/* Lookup the character ch in the mapping. If the character
8297 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008298 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008299static PyObject *
Victor Stinner22168992011-11-20 17:09:18 +01008300charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008301{
Christian Heimes217cfd12007-12-02 14:31:20 +00008302 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303 PyObject *x;
8304
8305 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008306 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307 x = PyObject_GetItem(mapping, w);
8308 Py_DECREF(w);
8309 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8311 /* No mapping found means: mapping is undefined. */
8312 PyErr_Clear();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02008313 Py_RETURN_NONE;
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 } else
8315 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008316 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008317 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008318 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008319 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008320 long value = PyLong_AS_LONG(x);
8321 if (value < 0 || value > 255) {
8322 PyErr_SetString(PyExc_TypeError,
8323 "character mapping must be in range(256)");
8324 Py_DECREF(x);
8325 return NULL;
8326 }
8327 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008328 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008329 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008331 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008332 /* wrong return value */
8333 PyErr_Format(PyExc_TypeError,
8334 "character mapping must return integer, bytes or None, not %.400s",
8335 x->ob_type->tp_name);
8336 Py_DECREF(x);
8337 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008338 }
8339}
8340
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008341static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008342charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008343{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008344 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8345 /* exponentially overallocate to minimize reallocations */
8346 if (requiredsize < 2*outsize)
8347 requiredsize = 2*outsize;
8348 if (_PyBytes_Resize(outobj, requiredsize))
8349 return -1;
8350 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008351}
8352
Benjamin Peterson14339b62009-01-31 16:36:08 +00008353typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008355} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008356/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008357 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358 space is available. Return a new reference to the object that
8359 was put in the output buffer, or Py_None, if the mapping was undefined
8360 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008361 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008362static charmapencode_result
Victor Stinner22168992011-11-20 17:09:18 +01008363charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008364 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008366 PyObject *rep;
8367 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008368 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369
Christian Heimes90aa7642007-12-19 02:45:37 +00008370 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008371 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008373 if (res == -1)
8374 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 if (outsize<requiredsize)
8376 if (charmapencode_resize(outobj, outpos, requiredsize))
8377 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008378 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 outstart[(*outpos)++] = (char)res;
8380 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008381 }
8382
8383 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008386 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 Py_DECREF(rep);
8388 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008389 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008390 if (PyLong_Check(rep)) {
8391 Py_ssize_t requiredsize = *outpos+1;
8392 if (outsize<requiredsize)
8393 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8394 Py_DECREF(rep);
8395 return enc_EXCEPTION;
8396 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008397 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008398 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008399 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008400 else {
8401 const char *repchars = PyBytes_AS_STRING(rep);
8402 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8403 Py_ssize_t requiredsize = *outpos+repsize;
8404 if (outsize<requiredsize)
8405 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8406 Py_DECREF(rep);
8407 return enc_EXCEPTION;
8408 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008409 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 memcpy(outstart + *outpos, repchars, repsize);
8411 *outpos += repsize;
8412 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008413 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008414 Py_DECREF(rep);
8415 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416}
8417
8418/* handle an error in PyUnicode_EncodeCharmap
8419 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008420static int
8421charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008422 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423 PyObject **exceptionObject,
Victor Stinner50149202015-09-22 00:26:54 +02008424 _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008425 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008426{
8427 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008428 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008429 Py_ssize_t newpos;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008430 enum PyUnicode_Kind kind;
8431 void *data;
8432 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008433 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008434 Py_ssize_t collstartpos = *inpos;
8435 Py_ssize_t collendpos = *inpos+1;
8436 Py_ssize_t collpos;
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008437 const char *encoding = "charmap";
8438 const char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008439 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008440 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008441 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008442
Benjamin Petersonbac79492012-01-14 13:34:47 -05008443 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008444 return -1;
8445 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 /* find all unencodable characters */
8447 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008448 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008449 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008450 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008451 val = encoding_map_lookup(ch, mapping);
8452 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 break;
8454 ++collendpos;
8455 continue;
8456 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008457
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008458 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8459 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 if (rep==NULL)
8461 return -1;
8462 else if (rep!=Py_None) {
8463 Py_DECREF(rep);
8464 break;
8465 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008466 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008467 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008468 }
8469 /* cache callback name lookup
8470 * (if not done yet, i.e. it's the first error) */
Victor Stinner50149202015-09-22 00:26:54 +02008471 if (*error_handler == _Py_ERROR_UNKNOWN)
Victor Stinner3d4226a2018-08-29 22:21:32 +02008472 *error_handler = _Py_GetErrorHandler(errors);
Victor Stinner50149202015-09-22 00:26:54 +02008473
8474 switch (*error_handler) {
8475 case _Py_ERROR_STRICT:
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008476 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008477 return -1;
Victor Stinner50149202015-09-22 00:26:54 +02008478
8479 case _Py_ERROR_REPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008480 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 x = charmapencode_output('?', mapping, res, respos);
8482 if (x==enc_EXCEPTION) {
8483 return -1;
8484 }
8485 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008486 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 return -1;
8488 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008489 }
8490 /* fall through */
Victor Stinner50149202015-09-22 00:26:54 +02008491 case _Py_ERROR_IGNORE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 *inpos = collendpos;
8493 break;
Victor Stinner50149202015-09-22 00:26:54 +02008494
8495 case _Py_ERROR_XMLCHARREFREPLACE:
Benjamin Peterson14339b62009-01-31 16:36:08 +00008496 /* generate replacement (temporarily (mis)uses p) */
8497 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008498 char buffer[2+29+1+1];
8499 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008500 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008501 for (cp = buffer; *cp; ++cp) {
8502 x = charmapencode_output(*cp, mapping, res, respos);
8503 if (x==enc_EXCEPTION)
8504 return -1;
8505 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008506 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 return -1;
8508 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008509 }
8510 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008511 *inpos = collendpos;
8512 break;
Victor Stinner50149202015-09-22 00:26:54 +02008513
Benjamin Peterson14339b62009-01-31 16:36:08 +00008514 default:
Victor Stinner50149202015-09-22 00:26:54 +02008515 repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008516 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008518 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008519 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008520 if (PyBytes_Check(repunicode)) {
8521 /* Directly copy bytes result to output. */
8522 Py_ssize_t outsize = PyBytes_Size(*res);
8523 Py_ssize_t requiredsize;
8524 repsize = PyBytes_Size(repunicode);
8525 requiredsize = *respos + repsize;
8526 if (requiredsize > outsize)
8527 /* Make room for all additional bytes. */
8528 if (charmapencode_resize(res, respos, requiredsize)) {
8529 Py_DECREF(repunicode);
8530 return -1;
8531 }
8532 memcpy(PyBytes_AsString(*res) + *respos,
8533 PyBytes_AsString(repunicode), repsize);
8534 *respos += repsize;
8535 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008536 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008537 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008538 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008539 /* generate replacement */
Benjamin Petersonbac79492012-01-14 13:34:47 -05008540 if (PyUnicode_READY(repunicode) == -1) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008541 Py_DECREF(repunicode);
8542 return -1;
8543 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008544 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008545 data = PyUnicode_DATA(repunicode);
8546 kind = PyUnicode_KIND(repunicode);
8547 for (index = 0; index < repsize; index++) {
8548 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8549 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008551 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 return -1;
8553 }
8554 else if (x==enc_FAILED) {
8555 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008556 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 return -1;
8558 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008559 }
8560 *inpos = newpos;
8561 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562 }
8563 return 0;
8564}
8565
Alexander Belopolsky40018472011-02-26 01:02:56 +00008566PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008567_PyUnicode_EncodeCharmap(PyObject *unicode,
8568 PyObject *mapping,
8569 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008570{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008571 /* output object */
8572 PyObject *res = NULL;
8573 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008574 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008575 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008576 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008577 Py_ssize_t respos = 0;
Victor Stinner50149202015-09-22 00:26:54 +02008578 PyObject *error_handler_obj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008579 PyObject *exc = NULL;
Victor Stinner50149202015-09-22 00:26:54 +02008580 _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
Victor Stinner69ed0f42013-04-09 21:48:24 +02008581 void *data;
8582 int kind;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008583
Benjamin Petersonbac79492012-01-14 13:34:47 -05008584 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008585 return NULL;
8586 size = PyUnicode_GET_LENGTH(unicode);
Victor Stinner69ed0f42013-04-09 21:48:24 +02008587 data = PyUnicode_DATA(unicode);
8588 kind = PyUnicode_KIND(unicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008589
Guido van Rossumd57fd912000-03-10 22:53:23 +00008590 /* Default to Latin-1 */
8591 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008592 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008593
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008594 /* allocate enough for a simple encoding without
8595 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008596 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597 if (res == NULL)
8598 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008599 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008601
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008602 while (inpos<size) {
Victor Stinner69ed0f42013-04-09 21:48:24 +02008603 Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008605 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 if (x==enc_EXCEPTION) /* error */
8607 goto onError;
8608 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008609 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 &exc,
Victor Stinner50149202015-09-22 00:26:54 +02008611 &error_handler, &error_handler_obj, errors,
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 &res, &respos)) {
8613 goto onError;
8614 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008615 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 else
8617 /* done with this character => adjust input position */
8618 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008619 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008620
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008621 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008622 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008623 if (_PyBytes_Resize(&res, respos) < 0)
8624 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008625
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008626 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008627 Py_XDECREF(error_handler_obj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 return res;
8629
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008631 Py_XDECREF(res);
8632 Py_XDECREF(exc);
Victor Stinner50149202015-09-22 00:26:54 +02008633 Py_XDECREF(error_handler_obj);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008634 return NULL;
8635}
8636
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008637/* Deprecated */
8638PyObject *
8639PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8640 Py_ssize_t size,
8641 PyObject *mapping,
8642 const char *errors)
8643{
8644 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02008645 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008646 if (unicode == NULL)
8647 return NULL;
8648 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8649 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008650 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008651}
8652
Alexander Belopolsky40018472011-02-26 01:02:56 +00008653PyObject *
8654PyUnicode_AsCharmapString(PyObject *unicode,
8655 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008656{
8657 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008658 PyErr_BadArgument();
8659 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008660 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008661 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008662}
8663
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008665static void
8666make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008668 Py_ssize_t startpos, Py_ssize_t endpos,
8669 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008670{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008671 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 *exceptionObject = _PyUnicodeTranslateError_Create(
8673 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008674 }
8675 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8677 goto onError;
8678 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8679 goto onError;
8680 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8681 goto onError;
8682 return;
8683 onError:
Serhiy Storchaka505ff752014-02-09 13:33:53 +02008684 Py_CLEAR(*exceptionObject);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008685 }
8686}
8687
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008688/* error handling callback helper:
8689 build arguments, call the callback and check the arguments,
8690 put the result into newpos and return the replacement string, which
8691 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008692static PyObject *
8693unicode_translate_call_errorhandler(const char *errors,
8694 PyObject **errorHandler,
8695 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008696 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008697 Py_ssize_t startpos, Py_ssize_t endpos,
8698 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008699{
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008700 static const char *argparse = "Un;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008701
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008702 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008703 PyObject *restuple;
8704 PyObject *resunicode;
8705
8706 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008708 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008709 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008710 }
8711
8712 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008713 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008714 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716
Victor Stinnerde4ae3d2016-12-04 22:59:09 +01008717 restuple = PyObject_CallFunctionObjArgs(
8718 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008719 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008720 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008721 if (!PyTuple_Check(restuple)) {
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008722 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008723 Py_DECREF(restuple);
8724 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008725 }
Serhiy Storchakaf8d7d412016-10-23 15:12:25 +03008726 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00008727 &resunicode, &i_newpos)) {
8728 Py_DECREF(restuple);
8729 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008730 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008731 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008733 else
8734 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008735 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Victor Stinnera33bce02014-07-04 22:47:46 +02008736 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008737 Py_DECREF(restuple);
8738 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008739 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008740 Py_INCREF(resunicode);
8741 Py_DECREF(restuple);
8742 return resunicode;
8743}
8744
8745/* Lookup the character ch in the mapping and put the result in result,
8746 which must be decrefed by the caller.
8747 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008748static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008750{
Christian Heimes217cfd12007-12-02 14:31:20 +00008751 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008752 PyObject *x;
8753
8754 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008755 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008756 x = PyObject_GetItem(mapping, w);
8757 Py_DECREF(w);
8758 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008759 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8760 /* No mapping found means: use 1:1 mapping. */
8761 PyErr_Clear();
8762 *result = NULL;
8763 return 0;
8764 } else
8765 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008766 }
8767 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 *result = x;
8769 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008770 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008771 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008772 long value = PyLong_AS_LONG(x);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008773 if (value < 0 || value > MAX_UNICODE) {
8774 PyErr_Format(PyExc_ValueError,
8775 "character mapping must be in range(0x%x)",
8776 MAX_UNICODE+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008777 Py_DECREF(x);
8778 return -1;
8779 }
8780 *result = x;
8781 return 0;
8782 }
8783 else if (PyUnicode_Check(x)) {
8784 *result = x;
8785 return 0;
8786 }
8787 else {
8788 /* wrong return value */
8789 PyErr_SetString(PyExc_TypeError,
8790 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008791 Py_DECREF(x);
8792 return -1;
8793 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008794}
Victor Stinner1194ea02014-04-04 19:37:40 +02008795
8796/* lookup the character, write the result into the writer.
8797 Return 1 if the result was written into the writer, return 0 if the mapping
8798 was undefined, raise an exception return -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008799static int
Victor Stinner1194ea02014-04-04 19:37:40 +02008800charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
8801 _PyUnicodeWriter *writer)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008802{
Victor Stinner1194ea02014-04-04 19:37:40 +02008803 PyObject *item;
8804
8805 if (charmaptranslate_lookup(ch, mapping, &item))
Benjamin Peterson29060642009-01-31 22:14:21 +00008806 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008807
8808 if (item == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008809 /* not found => default to 1:1 mapping */
Victor Stinner1194ea02014-04-04 19:37:40 +02008810 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008811 return -1;
Benjamin Peterson29060642009-01-31 22:14:21 +00008812 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008813 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008814 }
Victor Stinner1194ea02014-04-04 19:37:40 +02008815
8816 if (item == Py_None) {
8817 Py_DECREF(item);
8818 return 0;
8819 }
8820
8821 if (PyLong_Check(item)) {
Victor Stinner4ff33af2014-04-05 11:56:37 +02008822 long ch = (Py_UCS4)PyLong_AS_LONG(item);
8823 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8824 used it */
Victor Stinner1194ea02014-04-04 19:37:40 +02008825 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
8826 Py_DECREF(item);
8827 return -1;
8828 }
8829 Py_DECREF(item);
8830 return 1;
8831 }
8832
8833 if (!PyUnicode_Check(item)) {
8834 Py_DECREF(item);
Benjamin Peterson29060642009-01-31 22:14:21 +00008835 return -1;
Victor Stinner1194ea02014-04-04 19:37:40 +02008836 }
8837
8838 if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
8839 Py_DECREF(item);
8840 return -1;
8841 }
8842
8843 Py_DECREF(item);
8844 return 1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008845}
8846
Victor Stinner89a76ab2014-04-05 11:44:04 +02008847static int
8848unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
8849 Py_UCS1 *translate)
8850{
Benjamin Peterson1365de72014-04-07 20:15:41 -04008851 PyObject *item = NULL;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008852 int ret = 0;
8853
Victor Stinner89a76ab2014-04-05 11:44:04 +02008854 if (charmaptranslate_lookup(ch, mapping, &item)) {
8855 return -1;
8856 }
8857
8858 if (item == Py_None) {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008859 /* deletion */
Victor Stinner872b2912014-04-05 14:27:07 +02008860 translate[ch] = 0xfe;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008861 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008862 else if (item == NULL) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008863 /* not found => default to 1:1 mapping */
8864 translate[ch] = ch;
8865 return 1;
8866 }
Benjamin Peterson1365de72014-04-07 20:15:41 -04008867 else if (PyLong_Check(item)) {
Victor Stinner4dd25252014-04-08 09:14:21 +02008868 long replace = PyLong_AS_LONG(item);
Victor Stinner4ff33af2014-04-05 11:56:37 +02008869 /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
8870 used it */
8871 if (127 < replace) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008872 /* invalid character or character outside ASCII:
8873 skip the fast translate */
8874 goto exit;
8875 }
8876 translate[ch] = (Py_UCS1)replace;
8877 }
8878 else if (PyUnicode_Check(item)) {
8879 Py_UCS4 replace;
8880
8881 if (PyUnicode_READY(item) == -1) {
8882 Py_DECREF(item);
8883 return -1;
8884 }
8885 if (PyUnicode_GET_LENGTH(item) != 1)
8886 goto exit;
8887
8888 replace = PyUnicode_READ_CHAR(item, 0);
8889 if (replace > 127)
8890 goto exit;
8891 translate[ch] = (Py_UCS1)replace;
8892 }
8893 else {
Benjamin Peterson1365de72014-04-07 20:15:41 -04008894 /* not None, NULL, long or unicode */
Victor Stinner89a76ab2014-04-05 11:44:04 +02008895 goto exit;
8896 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02008897 ret = 1;
8898
Benjamin Peterson1365de72014-04-07 20:15:41 -04008899 exit:
8900 Py_DECREF(item);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008901 return ret;
8902}
8903
8904/* Fast path for ascii => ascii translation. Return 1 if the whole string
8905 was translated into writer, return 0 if the input string was partially
8906 translated into writer, raise an exception and return -1 on error. */
8907static int
8908unicode_fast_translate(PyObject *input, PyObject *mapping,
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008909 _PyUnicodeWriter *writer, int ignore,
8910 Py_ssize_t *input_pos)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008911{
Victor Stinner872b2912014-04-05 14:27:07 +02008912 Py_UCS1 ascii_table[128], ch, ch2;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008913 Py_ssize_t len;
8914 Py_UCS1 *in, *end, *out;
Victor Stinner872b2912014-04-05 14:27:07 +02008915 int res = 0;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008916
Victor Stinner89a76ab2014-04-05 11:44:04 +02008917 len = PyUnicode_GET_LENGTH(input);
8918
Victor Stinner872b2912014-04-05 14:27:07 +02008919 memset(ascii_table, 0xff, 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008920
8921 in = PyUnicode_1BYTE_DATA(input);
8922 end = in + len;
8923
8924 assert(PyUnicode_IS_ASCII(writer->buffer));
8925 assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
8926 out = PyUnicode_1BYTE_DATA(writer->buffer);
8927
Victor Stinner872b2912014-04-05 14:27:07 +02008928 for (; in < end; in++) {
Victor Stinner89a76ab2014-04-05 11:44:04 +02008929 ch = *in;
Victor Stinner872b2912014-04-05 14:27:07 +02008930 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008931 if (ch2 == 0xff) {
Victor Stinner872b2912014-04-05 14:27:07 +02008932 int translate = unicode_fast_translate_lookup(mapping, ch,
8933 ascii_table);
8934 if (translate < 0)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008935 return -1;
Victor Stinner872b2912014-04-05 14:27:07 +02008936 if (translate == 0)
8937 goto exit;
8938 ch2 = ascii_table[ch];
Victor Stinner89a76ab2014-04-05 11:44:04 +02008939 }
Victor Stinner872b2912014-04-05 14:27:07 +02008940 if (ch2 == 0xfe) {
8941 if (ignore)
8942 continue;
8943 goto exit;
8944 }
8945 assert(ch2 < 128);
Victor Stinner89a76ab2014-04-05 11:44:04 +02008946 *out = ch2;
Victor Stinner872b2912014-04-05 14:27:07 +02008947 out++;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008948 }
Victor Stinner872b2912014-04-05 14:27:07 +02008949 res = 1;
8950
8951exit:
8952 writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
Victor Stinner6c9aa8f2016-03-01 21:30:30 +01008953 *input_pos = in - PyUnicode_1BYTE_DATA(input);
Victor Stinner872b2912014-04-05 14:27:07 +02008954 return res;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008955}
8956
Victor Stinner3222da22015-10-01 22:07:32 +02008957static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008958_PyUnicode_TranslateCharmap(PyObject *input,
8959 PyObject *mapping,
8960 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008961{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008962 /* input object */
Victor Stinner1194ea02014-04-04 19:37:40 +02008963 char *data;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008964 Py_ssize_t size, i;
8965 int kind;
8966 /* output buffer */
Victor Stinner1194ea02014-04-04 19:37:40 +02008967 _PyUnicodeWriter writer;
8968 /* error handler */
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02008969 const char *reason = "character maps to <undefined>";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008970 PyObject *errorHandler = NULL;
8971 PyObject *exc = NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008972 int ignore;
Victor Stinner89a76ab2014-04-05 11:44:04 +02008973 int res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008974
Guido van Rossumd57fd912000-03-10 22:53:23 +00008975 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008976 PyErr_BadArgument();
8977 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008978 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008980 if (PyUnicode_READY(input) == -1)
8981 return NULL;
Victor Stinner1194ea02014-04-04 19:37:40 +02008982 data = (char*)PyUnicode_DATA(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008983 kind = PyUnicode_KIND(input);
8984 size = PyUnicode_GET_LENGTH(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008985
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03008986 if (size == 0)
8987 return PyUnicode_FromObject(input);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008988
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008989 /* allocate enough for a simple 1:1 translation without
8990 replacements, if we need more, we'll resize */
Victor Stinner1194ea02014-04-04 19:37:40 +02008991 _PyUnicodeWriter_Init(&writer);
8992 if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008993 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008994
Victor Stinner872b2912014-04-05 14:27:07 +02008995 ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
8996
Victor Stinner33798672016-03-01 21:59:58 +01008997 if (PyUnicode_READY(input) == -1)
Victor Stinner89a76ab2014-04-05 11:44:04 +02008998 return NULL;
Victor Stinner33798672016-03-01 21:59:58 +01008999 if (PyUnicode_IS_ASCII(input)) {
9000 res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
9001 if (res < 0) {
9002 _PyUnicodeWriter_Dealloc(&writer);
9003 return NULL;
9004 }
9005 if (res == 1)
9006 return _PyUnicodeWriter_Finish(&writer);
Victor Stinner89a76ab2014-04-05 11:44:04 +02009007 }
Victor Stinner33798672016-03-01 21:59:58 +01009008 else {
9009 i = 0;
9010 }
Victor Stinner89a76ab2014-04-05 11:44:04 +02009011
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009013 /* try to encode it */
Victor Stinner1194ea02014-04-04 19:37:40 +02009014 int translate;
9015 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
9016 Py_ssize_t newpos;
9017 /* startpos for collecting untranslatable chars */
9018 Py_ssize_t collstart;
9019 Py_ssize_t collend;
Victor Stinner1194ea02014-04-04 19:37:40 +02009020 Py_UCS4 ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009021
Victor Stinner1194ea02014-04-04 19:37:40 +02009022 ch = PyUnicode_READ(kind, data, i);
9023 translate = charmaptranslate_output(ch, mapping, &writer);
9024 if (translate < 0)
9025 goto onError;
9026
9027 if (translate != 0) {
9028 /* it worked => adjust input pointer */
9029 ++i;
9030 continue;
9031 }
9032
9033 /* untranslatable character */
9034 collstart = i;
9035 collend = i+1;
9036
9037 /* find all untranslatable characters */
9038 while (collend < size) {
9039 PyObject *x;
9040 ch = PyUnicode_READ(kind, data, collend);
9041 if (charmaptranslate_lookup(ch, mapping, &x))
Benjamin Peterson14339b62009-01-31 16:36:08 +00009042 goto onError;
Victor Stinner1194ea02014-04-04 19:37:40 +02009043 Py_XDECREF(x);
9044 if (x != Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00009045 break;
Victor Stinner1194ea02014-04-04 19:37:40 +02009046 ++collend;
9047 }
9048
9049 if (ignore) {
9050 i = collend;
9051 }
9052 else {
9053 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
9054 reason, input, &exc,
9055 collstart, collend, &newpos);
9056 if (repunicode == NULL)
9057 goto onError;
9058 if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009059 Py_DECREF(repunicode);
Victor Stinner1194ea02014-04-04 19:37:40 +02009060 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009061 }
Victor Stinner1194ea02014-04-04 19:37:40 +02009062 Py_DECREF(repunicode);
9063 i = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009064 }
9065 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009066 Py_XDECREF(exc);
9067 Py_XDECREF(errorHandler);
Victor Stinner1194ea02014-04-04 19:37:40 +02009068 return _PyUnicodeWriter_Finish(&writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009069
Benjamin Peterson29060642009-01-31 22:14:21 +00009070 onError:
Victor Stinner1194ea02014-04-04 19:37:40 +02009071 _PyUnicodeWriter_Dealloc(&writer);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009072 Py_XDECREF(exc);
9073 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009074 return NULL;
9075}
9076
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077/* Deprecated. Use PyUnicode_Translate instead. */
9078PyObject *
9079PyUnicode_TranslateCharmap(const Py_UNICODE *p,
9080 Py_ssize_t size,
9081 PyObject *mapping,
9082 const char *errors)
9083{
Christian Heimes5f520f42012-09-11 14:03:25 +02009084 PyObject *result;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009085 PyObject *unicode = PyUnicode_FromWideChar(p, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009086 if (!unicode)
9087 return NULL;
Christian Heimes5f520f42012-09-11 14:03:25 +02009088 result = _PyUnicode_TranslateCharmap(unicode, mapping, errors);
9089 Py_DECREF(unicode);
9090 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091}
9092
Alexander Belopolsky40018472011-02-26 01:02:56 +00009093PyObject *
9094PyUnicode_Translate(PyObject *str,
9095 PyObject *mapping,
9096 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009097{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009098 if (ensure_unicode(str) < 0)
Christian Heimes5f520f42012-09-11 14:03:25 +02009099 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009100 return _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009101}
Tim Petersced69f82003-09-16 20:30:58 +00009102
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009103PyObject *
9104_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
9105{
9106 if (!PyUnicode_Check(unicode)) {
9107 PyErr_BadInternalCall();
9108 return NULL;
9109 }
9110 if (PyUnicode_READY(unicode) == -1)
9111 return NULL;
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009112 if (PyUnicode_IS_ASCII(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009113 /* If the string is already ASCII, just return the same string */
9114 Py_INCREF(unicode);
9115 return unicode;
9116 }
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009117
9118 Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
9119 PyObject *result = PyUnicode_New(len, 127);
9120 if (result == NULL) {
9121 return NULL;
9122 }
9123
9124 Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
9125 int kind = PyUnicode_KIND(unicode);
9126 const void *data = PyUnicode_DATA(unicode);
9127 Py_ssize_t i;
9128 for (i = 0; i < len; ++i) {
9129 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9130 if (ch < 127) {
9131 out[i] = ch;
9132 }
9133 else if (Py_UNICODE_ISSPACE(ch)) {
9134 out[i] = ' ';
9135 }
9136 else {
9137 int decimal = Py_UNICODE_TODECIMAL(ch);
9138 if (decimal < 0) {
9139 out[i] = '?';
INADA Naoki16dfca42018-07-14 12:06:43 +09009140 out[i+1] = '\0';
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009141 _PyUnicode_LENGTH(result) = i + 1;
9142 break;
9143 }
9144 out[i] = '0' + decimal;
9145 }
9146 }
9147
INADA Naoki16dfca42018-07-14 12:06:43 +09009148 assert(_PyUnicode_CheckConsistency(result, 1));
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02009149 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009150}
9151
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009152PyObject *
9153PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
9154 Py_ssize_t length)
9155{
Victor Stinnerf0124502011-11-21 23:12:56 +01009156 PyObject *decimal;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009157 Py_ssize_t i;
Victor Stinnerf0124502011-11-21 23:12:56 +01009158 Py_UCS4 maxchar;
9159 enum PyUnicode_Kind kind;
9160 void *data;
9161
Victor Stinner99d7ad02012-02-22 13:37:39 +01009162 maxchar = 127;
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009163 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009164 Py_UCS4 ch = s[i];
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009165 if (ch > 127) {
9166 int decimal = Py_UNICODE_TODECIMAL(ch);
9167 if (decimal >= 0)
Victor Stinnerf0124502011-11-21 23:12:56 +01009168 ch = '0' + decimal;
Benjamin Peterson7e303732013-06-10 09:19:46 -07009169 maxchar = Py_MAX(maxchar, ch);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009170 }
9171 }
Victor Stinnerf0124502011-11-21 23:12:56 +01009172
9173 /* Copy to a new string */
9174 decimal = PyUnicode_New(length, maxchar);
9175 if (decimal == NULL)
9176 return decimal;
9177 kind = PyUnicode_KIND(decimal);
9178 data = PyUnicode_DATA(decimal);
9179 /* Iterate over code points */
9180 for (i = 0; i < length; i++) {
Victor Stinner12174a52014-08-15 23:17:38 +02009181 Py_UCS4 ch = s[i];
Victor Stinnerf0124502011-11-21 23:12:56 +01009182 if (ch > 127) {
9183 int decimal = Py_UNICODE_TODECIMAL(ch);
9184 if (decimal >= 0)
9185 ch = '0' + decimal;
9186 }
9187 PyUnicode_WRITE(kind, data, i, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009188 }
Victor Stinnerd3df8ab2011-11-22 01:22:34 +01009189 return unicode_result(decimal);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00009190}
Guido van Rossum9e896b32000-04-05 20:11:21 +00009191/* --- Decimal Encoder ---------------------------------------------------- */
9192
Alexander Belopolsky40018472011-02-26 01:02:56 +00009193int
9194PyUnicode_EncodeDecimal(Py_UNICODE *s,
9195 Py_ssize_t length,
9196 char *output,
9197 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00009198{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009199 PyObject *unicode;
Victor Stinner6345be92011-11-25 20:09:01 +01009200 Py_ssize_t i;
Victor Stinner42bf7752011-11-21 22:52:58 +01009201 enum PyUnicode_Kind kind;
9202 void *data;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009203
9204 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009205 PyErr_BadArgument();
9206 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009207 }
9208
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +02009209 unicode = PyUnicode_FromWideChar(s, length);
Victor Stinner42bf7752011-11-21 22:52:58 +01009210 if (unicode == NULL)
9211 return -1;
9212
Victor Stinner42bf7752011-11-21 22:52:58 +01009213 kind = PyUnicode_KIND(unicode);
9214 data = PyUnicode_DATA(unicode);
9215
Victor Stinnerb84d7232011-11-22 01:50:07 +01009216 for (i=0; i < length; ) {
Victor Stinner6345be92011-11-25 20:09:01 +01009217 PyObject *exc;
9218 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00009219 int decimal;
Victor Stinner6345be92011-11-25 20:09:01 +01009220 Py_ssize_t startpos;
9221
9222 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +00009223
Benjamin Peterson29060642009-01-31 22:14:21 +00009224 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009225 *output++ = ' ';
Victor Stinnerb84d7232011-11-22 01:50:07 +01009226 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009227 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00009228 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009229 decimal = Py_UNICODE_TODECIMAL(ch);
9230 if (decimal >= 0) {
9231 *output++ = '0' + decimal;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009232 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009233 continue;
9234 }
9235 if (0 < ch && ch < 256) {
9236 *output++ = (char)ch;
Victor Stinnerb84d7232011-11-22 01:50:07 +01009237 i++;
Benjamin Peterson29060642009-01-31 22:14:21 +00009238 continue;
9239 }
Victor Stinner6345be92011-11-25 20:09:01 +01009240
Victor Stinner42bf7752011-11-21 22:52:58 +01009241 startpos = i;
Victor Stinner6345be92011-11-25 20:09:01 +01009242 exc = NULL;
9243 raise_encode_exception(&exc, "decimal", unicode,
9244 startpos, startpos+1,
9245 "invalid decimal Unicode string");
9246 Py_XDECREF(exc);
9247 Py_DECREF(unicode);
9248 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009249 }
9250 /* 0-terminate the output string */
9251 *output++ = '\0';
Victor Stinner42bf7752011-11-21 22:52:58 +01009252 Py_DECREF(unicode);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009253 return 0;
Guido van Rossum9e896b32000-04-05 20:11:21 +00009254}
9255
Guido van Rossumd57fd912000-03-10 22:53:23 +00009256/* --- Helpers ------------------------------------------------------------ */
9257
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009258/* helper macro to fixup start/end slice values */
9259#define ADJUST_INDICES(start, end, len) \
9260 if (end > len) \
9261 end = len; \
9262 else if (end < 0) { \
9263 end += len; \
9264 if (end < 0) \
9265 end = 0; \
9266 } \
9267 if (start < 0) { \
9268 start += len; \
9269 if (start < 0) \
9270 start = 0; \
9271 }
9272
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009273static Py_ssize_t
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009274any_find_slice(PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009275 Py_ssize_t start,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009276 Py_ssize_t end,
9277 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009278{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009279 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009280 void *buf1, *buf2;
9281 Py_ssize_t len1, len2, result;
9282
9283 kind1 = PyUnicode_KIND(s1);
9284 kind2 = PyUnicode_KIND(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009285 if (kind1 < kind2)
9286 return -1;
9287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 len1 = PyUnicode_GET_LENGTH(s1);
9289 len2 = PyUnicode_GET_LENGTH(s2);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009290 ADJUST_INDICES(start, end, len1);
9291 if (end - start < len2)
9292 return -1;
9293
9294 buf1 = PyUnicode_DATA(s1);
9295 buf2 = PyUnicode_DATA(s2);
9296 if (len2 == 1) {
9297 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
9298 result = findchar((const char *)buf1 + kind1*start,
9299 kind1, end - start, ch, direction);
9300 if (result == -1)
9301 return -1;
9302 else
9303 return start + result;
9304 }
9305
9306 if (kind2 != kind1) {
9307 buf2 = _PyUnicode_AsKind(s2, kind1);
9308 if (!buf2)
9309 return -2;
9310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311
Victor Stinner794d5672011-10-10 03:21:36 +02009312 if (direction > 0) {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009313 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009314 case PyUnicode_1BYTE_KIND:
9315 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9316 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9317 else
9318 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9319 break;
9320 case PyUnicode_2BYTE_KIND:
9321 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9322 break;
9323 case PyUnicode_4BYTE_KIND:
9324 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9325 break;
9326 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009327 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009328 }
9329 }
9330 else {
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009331 switch (kind1) {
Victor Stinner794d5672011-10-10 03:21:36 +02009332 case PyUnicode_1BYTE_KIND:
9333 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9334 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9335 else
9336 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9337 break;
9338 case PyUnicode_2BYTE_KIND:
9339 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9340 break;
9341 case PyUnicode_4BYTE_KIND:
9342 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9343 break;
9344 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009345 Py_UNREACHABLE();
Victor Stinner794d5672011-10-10 03:21:36 +02009346 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 }
9348
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009349 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009350 PyMem_Free(buf2);
9351
9352 return result;
9353}
9354
Victor Stinner59423e32018-11-26 13:40:01 +01009355/* _PyUnicode_InsertThousandsGrouping() helper functions */
9356#include "stringlib/localeutil.h"
9357
9358/**
9359 * InsertThousandsGrouping:
9360 * @writer: Unicode writer.
9361 * @n_buffer: Number of characters in @buffer.
9362 * @digits: Digits we're reading from. If count is non-NULL, this is unused.
9363 * @d_pos: Start of digits string.
9364 * @n_digits: The number of digits in the string, in which we want
9365 * to put the grouping chars.
9366 * @min_width: The minimum width of the digits in the output string.
9367 * Output will be zero-padded on the left to fill.
9368 * @grouping: see definition in localeconv().
9369 * @thousands_sep: see definition in localeconv().
9370 *
9371 * There are 2 modes: counting and filling. If @writer is NULL,
9372 * we are in counting mode, else filling mode.
9373 * If counting, the required buffer size is returned.
9374 * If filling, we know the buffer will be large enough, so we don't
9375 * need to pass in the buffer size.
9376 * Inserts thousand grouping characters (as defined by grouping and
9377 * thousands_sep) into @writer.
9378 *
9379 * Return value: -1 on error, number of characters otherwise.
9380 **/
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009381Py_ssize_t
Victor Stinner41a863c2012-02-24 00:37:51 +01009382_PyUnicode_InsertThousandsGrouping(
Victor Stinner59423e32018-11-26 13:40:01 +01009383 _PyUnicodeWriter *writer,
Victor Stinner41a863c2012-02-24 00:37:51 +01009384 Py_ssize_t n_buffer,
Victor Stinner59423e32018-11-26 13:40:01 +01009385 PyObject *digits,
9386 Py_ssize_t d_pos,
9387 Py_ssize_t n_digits,
Victor Stinner41a863c2012-02-24 00:37:51 +01009388 Py_ssize_t min_width,
Victor Stinner59423e32018-11-26 13:40:01 +01009389 const char *grouping,
9390 PyObject *thousands_sep,
Victor Stinner41a863c2012-02-24 00:37:51 +01009391 Py_UCS4 *maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392{
Victor Stinner59423e32018-11-26 13:40:01 +01009393 if (writer) {
9394 assert(digits != NULL);
9395 assert(maxchar == NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009396 }
9397 else {
Victor Stinner59423e32018-11-26 13:40:01 +01009398 assert(digits == NULL);
9399 assert(maxchar != NULL);
Victor Stinner41a863c2012-02-24 00:37:51 +01009400 }
Victor Stinner59423e32018-11-26 13:40:01 +01009401 assert(0 <= d_pos);
9402 assert(0 <= n_digits);
9403 assert(0 <= min_width);
9404 assert(grouping != NULL);
9405
9406 if (digits != NULL) {
9407 if (PyUnicode_READY(digits) == -1) {
9408 return -1;
Victor Stinner90f50d42012-02-24 01:44:47 +01009409 }
Victor Stinner59423e32018-11-26 13:40:01 +01009410 }
9411 if (PyUnicode_READY(thousands_sep) == -1) {
9412 return -1;
Victor Stinner41a863c2012-02-24 00:37:51 +01009413 }
9414
Victor Stinner59423e32018-11-26 13:40:01 +01009415 Py_ssize_t count = 0;
9416 Py_ssize_t n_zeros;
9417 int loop_broken = 0;
9418 int use_separator = 0; /* First time through, don't append the
9419 separator. They only go between
9420 groups. */
9421 Py_ssize_t buffer_pos;
9422 Py_ssize_t digits_pos;
9423 Py_ssize_t len;
9424 Py_ssize_t n_chars;
9425 Py_ssize_t remaining = n_digits; /* Number of chars remaining to
9426 be looked at */
9427 /* A generator that returns all of the grouping widths, until it
9428 returns 0. */
9429 GroupGenerator groupgen;
9430 GroupGenerator_init(&groupgen, grouping);
9431 const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
9432
9433 /* if digits are not grouped, thousands separator
9434 should be an empty string */
9435 assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
9436
9437 digits_pos = d_pos + n_digits;
9438 if (writer) {
9439 buffer_pos = writer->pos + n_buffer;
9440 assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
9441 assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 }
Victor Stinner59423e32018-11-26 13:40:01 +01009443 else {
9444 buffer_pos = n_buffer;
Victor Stinner90f50d42012-02-24 01:44:47 +01009445 }
Victor Stinner59423e32018-11-26 13:40:01 +01009446
9447 if (!writer) {
Victor Stinner41a863c2012-02-24 00:37:51 +01009448 *maxchar = 127;
Victor Stinner41a863c2012-02-24 00:37:51 +01009449 }
Victor Stinner59423e32018-11-26 13:40:01 +01009450
9451 while ((len = GroupGenerator_next(&groupgen)) > 0) {
9452 len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
9453 n_zeros = Py_MAX(0, len - remaining);
9454 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9455
9456 /* Use n_zero zero's and n_chars chars */
9457
9458 /* Count only, don't do anything. */
9459 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9460
9461 /* Copy into the writer. */
9462 InsertThousandsGrouping_fill(writer, &buffer_pos,
9463 digits, &digits_pos,
9464 n_chars, n_zeros,
9465 use_separator ? thousands_sep : NULL,
9466 thousands_sep_len, maxchar);
9467
9468 /* Use a separator next time. */
9469 use_separator = 1;
9470
9471 remaining -= n_chars;
9472 min_width -= len;
9473
9474 if (remaining <= 0 && min_width <= 0) {
9475 loop_broken = 1;
9476 break;
9477 }
9478 min_width -= thousands_sep_len;
9479 }
9480 if (!loop_broken) {
9481 /* We left the loop without using a break statement. */
9482
9483 len = Py_MAX(Py_MAX(remaining, min_width), 1);
9484 n_zeros = Py_MAX(0, len - remaining);
9485 n_chars = Py_MAX(0, Py_MIN(remaining, len));
9486
9487 /* Use n_zero zero's and n_chars chars */
9488 count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
9489
9490 /* Copy into the writer. */
9491 InsertThousandsGrouping_fill(writer, &buffer_pos,
9492 digits, &digits_pos,
9493 n_chars, n_zeros,
9494 use_separator ? thousands_sep : NULL,
9495 thousands_sep_len, maxchar);
9496 }
9497 return count;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498}
9499
9500
Alexander Belopolsky40018472011-02-26 01:02:56 +00009501Py_ssize_t
9502PyUnicode_Count(PyObject *str,
9503 PyObject *substr,
9504 Py_ssize_t start,
9505 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009507 Py_ssize_t result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009508 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009509 void *buf1 = NULL, *buf2 = NULL;
9510 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009511
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009512 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009513 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009514
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009515 kind1 = PyUnicode_KIND(str);
9516 kind2 = PyUnicode_KIND(substr);
9517 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009518 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009519
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009520 len1 = PyUnicode_GET_LENGTH(str);
9521 len2 = PyUnicode_GET_LENGTH(substr);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009523 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009524 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009525
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009526 buf1 = PyUnicode_DATA(str);
9527 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009528 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009529 buf2 = _PyUnicode_AsKind(substr, kind1);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009530 if (!buf2)
9531 goto onError;
9532 }
9533
9534 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 case PyUnicode_1BYTE_KIND:
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009536 if (PyUnicode_IS_ASCII(str) && PyUnicode_IS_ASCII(substr))
Victor Stinnerc3cec782011-10-05 21:24:08 +02009537 result = asciilib_count(
9538 ((Py_UCS1*)buf1) + start, end - start,
9539 buf2, len2, PY_SSIZE_T_MAX
9540 );
9541 else
9542 result = ucs1lib_count(
9543 ((Py_UCS1*)buf1) + start, end - start,
9544 buf2, len2, PY_SSIZE_T_MAX
9545 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 break;
9547 case PyUnicode_2BYTE_KIND:
9548 result = ucs2lib_count(
9549 ((Py_UCS2*)buf1) + start, end - start,
9550 buf2, len2, PY_SSIZE_T_MAX
9551 );
9552 break;
9553 case PyUnicode_4BYTE_KIND:
9554 result = ucs4lib_count(
9555 ((Py_UCS4*)buf1) + start, end - start,
9556 buf2, len2, PY_SSIZE_T_MAX
9557 );
9558 break;
9559 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009560 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009562
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009563 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009564 PyMem_Free(buf2);
9565
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009567 onError:
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009568 if (kind2 != kind1 && buf2)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569 PyMem_Free(buf2);
9570 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009571}
9572
Alexander Belopolsky40018472011-02-26 01:02:56 +00009573Py_ssize_t
9574PyUnicode_Find(PyObject *str,
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009575 PyObject *substr,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009576 Py_ssize_t start,
9577 Py_ssize_t end,
9578 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009580 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009581 return -2;
Tim Petersced69f82003-09-16 20:30:58 +00009582
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009583 return any_find_slice(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009584}
9585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009586Py_ssize_t
9587PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9588 Py_ssize_t start, Py_ssize_t end,
9589 int direction)
9590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009591 int kind;
Xiang Zhangb2110682016-12-20 22:52:33 +08009592 Py_ssize_t len, result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 if (PyUnicode_READY(str) == -1)
9594 return -2;
Xiang Zhangb2110682016-12-20 22:52:33 +08009595 len = PyUnicode_GET_LENGTH(str);
9596 ADJUST_INDICES(start, end, len);
9597 if (end - start < 1)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +02009598 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009599 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009600 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9601 kind, end-start, ch, direction);
9602 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009603 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009604 else
9605 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009606}
9607
Alexander Belopolsky40018472011-02-26 01:02:56 +00009608static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009609tailmatch(PyObject *self,
9610 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009611 Py_ssize_t start,
9612 Py_ssize_t end,
9613 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009615 int kind_self;
9616 int kind_sub;
9617 void *data_self;
9618 void *data_sub;
9619 Py_ssize_t offset;
9620 Py_ssize_t i;
9621 Py_ssize_t end_sub;
9622
9623 if (PyUnicode_READY(self) == -1 ||
9624 PyUnicode_READY(substring) == -1)
Victor Stinner18aa4472013-01-03 03:18:09 +01009625 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9628 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009629 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009630 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009631
Serhiy Storchakad4ea03c2015-05-31 09:15:51 +03009632 if (PyUnicode_GET_LENGTH(substring) == 0)
9633 return 1;
9634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009635 kind_self = PyUnicode_KIND(self);
9636 data_self = PyUnicode_DATA(self);
9637 kind_sub = PyUnicode_KIND(substring);
9638 data_sub = PyUnicode_DATA(substring);
9639 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9640
9641 if (direction > 0)
9642 offset = end;
9643 else
9644 offset = start;
9645
9646 if (PyUnicode_READ(kind_self, data_self, offset) ==
9647 PyUnicode_READ(kind_sub, data_sub, 0) &&
9648 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9649 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9650 /* If both are of the same kind, memcmp is sufficient */
9651 if (kind_self == kind_sub) {
9652 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009653 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009654 data_sub,
9655 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009656 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009657 }
Martin Pantere26da7c2016-06-02 10:07:09 +00009658 /* otherwise we have to compare each character by first accessing it */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009659 else {
9660 /* We do not need to compare 0 and len(substring)-1 because
9661 the if statement above ensured already that they are equal
9662 when we end up here. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 for (i = 1; i < end_sub; ++i) {
9664 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9665 PyUnicode_READ(kind_sub, data_sub, i))
9666 return 0;
9667 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009668 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009669 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670 }
9671
9672 return 0;
9673}
9674
Alexander Belopolsky40018472011-02-26 01:02:56 +00009675Py_ssize_t
9676PyUnicode_Tailmatch(PyObject *str,
9677 PyObject *substr,
9678 Py_ssize_t start,
9679 Py_ssize_t end,
9680 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009681{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009682 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009683 return -1;
Tim Petersced69f82003-09-16 20:30:58 +00009684
Serhiy Storchaka21a663e2016-04-13 15:37:23 +03009685 return tailmatch(str, substr, start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009686}
9687
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009688static PyObject *
9689ascii_upper_or_lower(PyObject *self, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009691 Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9692 char *resdata, *data = PyUnicode_DATA(self);
9693 PyObject *res;
Tim Petersced69f82003-09-16 20:30:58 +00009694
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009695 res = PyUnicode_New(len, 127);
9696 if (res == NULL)
9697 return NULL;
9698 resdata = PyUnicode_DATA(res);
9699 if (lower)
9700 _Py_bytes_lower(resdata, data, len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009701 else
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009702 _Py_bytes_upper(resdata, data, len);
9703 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009704}
9705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706static Py_UCS4
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009707handle_capital_sigma(int kind, void *data, Py_ssize_t length, Py_ssize_t i)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009708{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009709 Py_ssize_t j;
9710 int final_sigma;
Victor Stinner0c39b1b2015-03-18 15:02:06 +01009711 Py_UCS4 c = 0; /* initialize to prevent gcc warning */
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009712 /* U+03A3 is in the Final_Sigma context when, it is found like this:
Tim Petersced69f82003-09-16 20:30:58 +00009713
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009714 \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
9715
9716 where ! is a negation and \p{xxx} is a character with property xxx.
9717 */
9718 for (j = i - 1; j >= 0; j--) {
9719 c = PyUnicode_READ(kind, data, j);
9720 if (!_PyUnicode_IsCaseIgnorable(c))
9721 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009722 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009723 final_sigma = j >= 0 && _PyUnicode_IsCased(c);
9724 if (final_sigma) {
9725 for (j = i + 1; j < length; j++) {
9726 c = PyUnicode_READ(kind, data, j);
9727 if (!_PyUnicode_IsCaseIgnorable(c))
9728 break;
9729 }
9730 final_sigma = j == length || !_PyUnicode_IsCased(c);
9731 }
9732 return (final_sigma) ? 0x3C2 : 0x3C3;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009733}
9734
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009735static int
9736lower_ucs4(int kind, void *data, Py_ssize_t length, Py_ssize_t i,
9737 Py_UCS4 c, Py_UCS4 *mapped)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009738{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009739 /* Obscure special case. */
9740 if (c == 0x3A3) {
9741 mapped[0] = handle_capital_sigma(kind, data, length, i);
9742 return 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009743 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009744 return _PyUnicode_ToLowerFull(c, mapped);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009745}
9746
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009747static Py_ssize_t
9748do_capitalize(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009749{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009750 Py_ssize_t i, k = 0;
9751 int n_res, j;
9752 Py_UCS4 c, mapped[3];
Tim Petersced69f82003-09-16 20:30:58 +00009753
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009754 c = PyUnicode_READ(kind, data, 0);
9755 n_res = _PyUnicode_ToUpperFull(c, mapped);
9756 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009757 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009758 res[k++] = mapped[j];
Guido van Rossumd57fd912000-03-10 22:53:23 +00009759 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009760 for (i = 1; i < length; i++) {
9761 c = PyUnicode_READ(kind, data, i);
9762 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9763 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009764 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009765 res[k++] = mapped[j];
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009766 }
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009767 }
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009768 return k;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009769}
9770
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009771static Py_ssize_t
9772do_swapcase(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
9773 Py_ssize_t i, k = 0;
9774
9775 for (i = 0; i < length; i++) {
9776 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9777 int n_res, j;
9778 if (Py_UNICODE_ISUPPER(c)) {
9779 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9780 }
9781 else if (Py_UNICODE_ISLOWER(c)) {
9782 n_res = _PyUnicode_ToUpperFull(c, mapped);
9783 }
9784 else {
9785 n_res = 1;
9786 mapped[0] = c;
9787 }
9788 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009789 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009790 res[k++] = mapped[j];
9791 }
9792 }
9793 return k;
9794}
9795
9796static Py_ssize_t
9797do_upper_or_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res,
9798 Py_UCS4 *maxchar, int lower)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009799{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009800 Py_ssize_t i, k = 0;
9801
9802 for (i = 0; i < length; i++) {
9803 Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
9804 int n_res, j;
9805 if (lower)
9806 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9807 else
9808 n_res = _PyUnicode_ToUpperFull(c, mapped);
9809 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009810 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009811 res[k++] = mapped[j];
9812 }
9813 }
9814 return k;
9815}
9816
9817static Py_ssize_t
9818do_upper(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9819{
9820 return do_upper_or_lower(kind, data, length, res, maxchar, 0);
9821}
9822
9823static Py_ssize_t
9824do_lower(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9825{
9826 return do_upper_or_lower(kind, data, length, res, maxchar, 1);
9827}
9828
Benjamin Petersone51757f2012-01-12 21:10:29 -05009829static Py_ssize_t
Benjamin Petersond5890c82012-01-14 13:23:30 -05009830do_casefold(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9831{
9832 Py_ssize_t i, k = 0;
9833
9834 for (i = 0; i < length; i++) {
9835 Py_UCS4 c = PyUnicode_READ(kind, data, i);
9836 Py_UCS4 mapped[3];
9837 int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
9838 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009839 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersond5890c82012-01-14 13:23:30 -05009840 res[k++] = mapped[j];
9841 }
9842 }
9843 return k;
9844}
9845
9846static Py_ssize_t
Benjamin Petersone51757f2012-01-12 21:10:29 -05009847do_title(int kind, void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
9848{
9849 Py_ssize_t i, k = 0;
9850 int previous_is_cased;
9851
9852 previous_is_cased = 0;
9853 for (i = 0; i < length; i++) {
9854 const Py_UCS4 c = PyUnicode_READ(kind, data, i);
9855 Py_UCS4 mapped[3];
9856 int n_res, j;
9857
9858 if (previous_is_cased)
9859 n_res = lower_ucs4(kind, data, length, i, c, mapped);
9860 else
9861 n_res = _PyUnicode_ToTitleFull(c, mapped);
9862
9863 for (j = 0; j < n_res; j++) {
Benjamin Peterson7e303732013-06-10 09:19:46 -07009864 *maxchar = Py_MAX(*maxchar, mapped[j]);
Benjamin Petersone51757f2012-01-12 21:10:29 -05009865 res[k++] = mapped[j];
9866 }
9867
9868 previous_is_cased = _PyUnicode_IsCased(c);
9869 }
9870 return k;
9871}
9872
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009873static PyObject *
9874case_operation(PyObject *self,
9875 Py_ssize_t (*perform)(int, void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
9876{
9877 PyObject *res = NULL;
9878 Py_ssize_t length, newlength = 0;
9879 int kind, outkind;
9880 void *data, *outdata;
9881 Py_UCS4 maxchar = 0, *tmp, *tmpend;
9882
Benjamin Petersoneea48462012-01-16 14:28:50 -05009883 assert(PyUnicode_IS_READY(self));
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009884
9885 kind = PyUnicode_KIND(self);
9886 data = PyUnicode_DATA(self);
9887 length = PyUnicode_GET_LENGTH(self);
Antoine Pitrou4e334242014-10-15 23:14:53 +02009888 if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
Benjamin Petersone1bd38c2014-10-15 11:47:36 -04009889 PyErr_SetString(PyExc_OverflowError, "string is too long");
9890 return NULL;
9891 }
Benjamin Peterson1e211ff2014-10-15 12:17:21 -04009892 tmp = PyMem_MALLOC(sizeof(Py_UCS4) * 3 * length);
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009893 if (tmp == NULL)
9894 return PyErr_NoMemory();
9895 newlength = perform(kind, data, length, tmp, &maxchar);
9896 res = PyUnicode_New(newlength, maxchar);
9897 if (res == NULL)
9898 goto leave;
9899 tmpend = tmp + newlength;
9900 outdata = PyUnicode_DATA(res);
9901 outkind = PyUnicode_KIND(res);
9902 switch (outkind) {
9903 case PyUnicode_1BYTE_KIND:
9904 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
9905 break;
9906 case PyUnicode_2BYTE_KIND:
9907 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
9908 break;
9909 case PyUnicode_4BYTE_KIND:
9910 memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
9911 break;
9912 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07009913 Py_UNREACHABLE();
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -05009914 }
9915 leave:
9916 PyMem_FREE(tmp);
9917 return res;
9918}
9919
Tim Peters8ce9f162004-08-27 01:49:32 +00009920PyObject *
9921PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009922{
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009923 PyObject *res;
9924 PyObject *fseq;
9925 Py_ssize_t seqlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009926 PyObject **items;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009927
Benjamin Peterson9743b2c2014-02-15 13:02:52 -05009928 fseq = PySequence_Fast(seq, "can only join an iterable");
Tim Peters05eba1f2004-08-27 21:32:02 +00009929 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009930 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009931 }
9932
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009933 /* NOTE: the following code can't call back into Python code,
9934 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009935 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009936
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009937 items = PySequence_Fast_ITEMS(fseq);
Tim Peters05eba1f2004-08-27 21:32:02 +00009938 seqlen = PySequence_Fast_GET_SIZE(fseq);
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009939 res = _PyUnicode_JoinArray(separator, items, seqlen);
9940 Py_DECREF(fseq);
9941 return res;
9942}
9943
9944PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +02009945_PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
Serhiy Storchakaea525a22016-09-06 22:07:53 +03009946{
9947 PyObject *res = NULL; /* the result */
9948 PyObject *sep = NULL;
9949 Py_ssize_t seplen;
9950 PyObject *item;
9951 Py_ssize_t sz, i, res_offset;
9952 Py_UCS4 maxchar;
9953 Py_UCS4 item_maxchar;
9954 int use_memcpy;
9955 unsigned char *res_data = NULL, *sep_data = NULL;
9956 PyObject *last_obj;
9957 unsigned int kind = 0;
9958
Tim Peters05eba1f2004-08-27 21:32:02 +00009959 /* If empty sequence, return u"". */
9960 if (seqlen == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +02009961 _Py_RETURN_UNICODE_EMPTY();
Tim Peters05eba1f2004-08-27 21:32:02 +00009962 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009963
Tim Peters05eba1f2004-08-27 21:32:02 +00009964 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009965 last_obj = NULL;
Victor Stinneracf47b82011-10-06 12:32:37 +02009966 if (seqlen == 1) {
9967 if (PyUnicode_CheckExact(items[0])) {
9968 res = items[0];
9969 Py_INCREF(res);
Victor Stinneracf47b82011-10-06 12:32:37 +02009970 return res;
9971 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009972 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009973 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009974 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009975 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009976 /* Set up sep and seplen */
9977 if (separator == NULL) {
9978 /* fall back to a blank space separator */
9979 sep = PyUnicode_FromOrdinal(' ');
9980 if (!sep)
9981 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009982 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009983 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009984 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009985 else {
9986 if (!PyUnicode_Check(separator)) {
9987 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +02009988 "separator: expected str instance,"
9989 " %.80s found",
9990 Py_TYPE(separator)->tp_name);
Victor Stinneracf47b82011-10-06 12:32:37 +02009991 goto onError;
9992 }
9993 if (PyUnicode_READY(separator))
9994 goto onError;
9995 sep = separator;
9996 seplen = PyUnicode_GET_LENGTH(separator);
9997 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9998 /* inc refcount to keep this code path symmetric with the
9999 above case of a blank separator */
10000 Py_INCREF(sep);
10001 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010002 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +000010003 }
10004
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010005 /* There are at least two things to join, or else we have a subclass
10006 * of str in the sequence.
10007 * Do a pre-pass to figure out the total amount of space we'll
10008 * need (sz), and see whether all argument are strings.
10009 */
10010 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +020010011#ifdef Py_DEBUG
10012 use_memcpy = 0;
10013#else
10014 use_memcpy = 1;
10015#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010016 for (i = 0; i < seqlen; i++) {
Xiang Zhangb0541f42017-01-10 10:52:00 +080010017 size_t add_sz;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010018 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +000010019 if (!PyUnicode_Check(item)) {
10020 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020010021 "sequence item %zd: expected str instance,"
10022 " %.80s found",
10023 i, Py_TYPE(item)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000010024 goto onError;
10025 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010026 if (PyUnicode_READY(item) == -1)
10027 goto onError;
Xiang Zhangb0541f42017-01-10 10:52:00 +080010028 add_sz = PyUnicode_GET_LENGTH(item);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010029 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010030 maxchar = Py_MAX(maxchar, item_maxchar);
Xiang Zhangb0541f42017-01-10 10:52:00 +080010031 if (i != 0) {
10032 add_sz += seplen;
10033 }
10034 if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010035 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010036 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010037 goto onError;
10038 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010039 sz += add_sz;
Victor Stinnerdd077322011-10-07 17:02:31 +020010040 if (use_memcpy && last_obj != NULL) {
10041 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
10042 use_memcpy = 0;
10043 }
10044 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010045 }
Tim Petersced69f82003-09-16 20:30:58 +000010046
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010047 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010048 if (res == NULL)
10049 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +000010050
Antoine Pitrouaf14b792008-08-07 21:50:41 +000010051 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +020010052#ifdef Py_DEBUG
10053 use_memcpy = 0;
10054#else
10055 if (use_memcpy) {
10056 res_data = PyUnicode_1BYTE_DATA(res);
10057 kind = PyUnicode_KIND(res);
10058 if (seplen != 0)
10059 sep_data = PyUnicode_1BYTE_DATA(sep);
10060 }
10061#endif
Victor Stinner4560f9c2013-04-14 18:56:46 +020010062 if (use_memcpy) {
10063 for (i = 0; i < seqlen; ++i) {
10064 Py_ssize_t itemlen;
10065 item = items[i];
10066
10067 /* Copy item, and maybe the separator. */
10068 if (i && seplen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010069 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010070 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010071 kind * seplen);
10072 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010073 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010074
10075 itemlen = PyUnicode_GET_LENGTH(item);
10076 if (itemlen != 0) {
Christian Heimesf051e432016-09-13 20:22:02 +020010077 memcpy(res_data,
Victor Stinnerdd077322011-10-07 17:02:31 +020010078 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010079 kind * itemlen);
10080 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +020010081 }
Victor Stinner4560f9c2013-04-14 18:56:46 +020010082 }
10083 assert(res_data == PyUnicode_1BYTE_DATA(res)
10084 + kind * PyUnicode_GET_LENGTH(res));
10085 }
10086 else {
10087 for (i = 0, res_offset = 0; i < seqlen; ++i) {
10088 Py_ssize_t itemlen;
10089 item = items[i];
10090
10091 /* Copy item, and maybe the separator. */
10092 if (i && seplen != 0) {
10093 _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
10094 res_offset += seplen;
10095 }
10096
10097 itemlen = PyUnicode_GET_LENGTH(item);
10098 if (itemlen != 0) {
Victor Stinnerd3f08822012-05-29 12:57:52 +020010099 _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
Victor Stinnerdd077322011-10-07 17:02:31 +020010100 res_offset += itemlen;
10101 }
Victor Stinner9ce5a832011-10-03 23:36:02 +020010102 }
Victor Stinnerdd077322011-10-07 17:02:31 +020010103 assert(res_offset == PyUnicode_GET_LENGTH(res));
Victor Stinner4560f9c2013-04-14 18:56:46 +020010104 }
Tim Peters8ce9f162004-08-27 01:49:32 +000010105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010106 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010107 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010109
Benjamin Peterson29060642009-01-31 22:14:21 +000010110 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +000010112 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010113 return NULL;
10114}
10115
Victor Stinnerd3f08822012-05-29 12:57:52 +020010116void
10117_PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10118 Py_UCS4 fill_char)
10119{
10120 const enum PyUnicode_Kind kind = PyUnicode_KIND(unicode);
Victor Stinner163403a2018-11-27 12:41:17 +010010121 void *data = PyUnicode_DATA(unicode);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010122 assert(PyUnicode_IS_READY(unicode));
10123 assert(unicode_modifiable(unicode));
10124 assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
10125 assert(start >= 0);
10126 assert(start + length <= PyUnicode_GET_LENGTH(unicode));
Victor Stinner59423e32018-11-26 13:40:01 +010010127 unicode_fill(kind, data, fill_char, start, length);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010128}
10129
Victor Stinner3fe55312012-01-04 00:33:50 +010010130Py_ssize_t
10131PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
10132 Py_UCS4 fill_char)
10133{
10134 Py_ssize_t maxlen;
Victor Stinner3fe55312012-01-04 00:33:50 +010010135
10136 if (!PyUnicode_Check(unicode)) {
10137 PyErr_BadInternalCall();
10138 return -1;
10139 }
10140 if (PyUnicode_READY(unicode) == -1)
10141 return -1;
10142 if (unicode_check_modifiable(unicode))
10143 return -1;
10144
Victor Stinnerd3f08822012-05-29 12:57:52 +020010145 if (start < 0) {
10146 PyErr_SetString(PyExc_IndexError, "string index out of range");
10147 return -1;
10148 }
Victor Stinner3fe55312012-01-04 00:33:50 +010010149 if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
10150 PyErr_SetString(PyExc_ValueError,
10151 "fill character is bigger than "
10152 "the string maximum character");
10153 return -1;
10154 }
10155
10156 maxlen = PyUnicode_GET_LENGTH(unicode) - start;
10157 length = Py_MIN(maxlen, length);
10158 if (length <= 0)
10159 return 0;
10160
Victor Stinnerd3f08822012-05-29 12:57:52 +020010161 _PyUnicode_FastFill(unicode, start, length, fill_char);
Victor Stinner3fe55312012-01-04 00:33:50 +010010162 return length;
10163}
10164
Victor Stinner9310abb2011-10-05 00:59:23 +020010165static PyObject *
10166pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010167 Py_ssize_t left,
10168 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010170{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 PyObject *u;
10172 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010173 int kind;
10174 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010175
10176 if (left < 0)
10177 left = 0;
10178 if (right < 0)
10179 right = 0;
10180
Victor Stinnerc4b49542011-12-11 22:44:26 +010010181 if (left == 0 && right == 0)
10182 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010184 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
10185 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +000010186 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
10187 return NULL;
10188 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010190 maxchar = Py_MAX(maxchar, fill);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010192 if (!u)
10193 return NULL;
10194
10195 kind = PyUnicode_KIND(u);
10196 data = PyUnicode_DATA(u);
10197 if (left)
Victor Stinner59423e32018-11-26 13:40:01 +010010198 unicode_fill(kind, data, fill, 0, left);
Victor Stinner6c7a52a2011-09-28 21:39:17 +020010199 if (right)
Victor Stinner59423e32018-11-26 13:40:01 +010010200 unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerd3f08822012-05-29 12:57:52 +020010201 _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010202 assert(_PyUnicode_CheckConsistency(u, 1));
10203 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010204}
10205
Alexander Belopolsky40018472011-02-26 01:02:56 +000010206PyObject *
10207PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010208{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010210
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010211 if (ensure_unicode(string) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010212 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010213
Benjamin Petersonead6b532011-12-20 17:23:42 -060010214 switch (PyUnicode_KIND(string)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010216 if (PyUnicode_IS_ASCII(string))
10217 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010218 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010219 PyUnicode_GET_LENGTH(string), keepends);
10220 else
10221 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010222 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010223 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 break;
10225 case PyUnicode_2BYTE_KIND:
10226 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010227 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 PyUnicode_GET_LENGTH(string), keepends);
10229 break;
10230 case PyUnicode_4BYTE_KIND:
10231 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010232 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 PyUnicode_GET_LENGTH(string), keepends);
10234 break;
10235 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010236 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010238 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010239}
10240
Alexander Belopolsky40018472011-02-26 01:02:56 +000010241static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010242split(PyObject *self,
10243 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010244 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010245{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010246 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 void *buf1, *buf2;
10248 Py_ssize_t len1, len2;
10249 PyObject* out;
10250
Guido van Rossumd57fd912000-03-10 22:53:23 +000010251 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010252 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 if (PyUnicode_READY(self) == -1)
10255 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010256
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010258 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010259 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010260 if (PyUnicode_IS_ASCII(self))
10261 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010262 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010263 PyUnicode_GET_LENGTH(self), maxcount
10264 );
10265 else
10266 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010267 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010268 PyUnicode_GET_LENGTH(self), maxcount
10269 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 case PyUnicode_2BYTE_KIND:
10271 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010272 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 PyUnicode_GET_LENGTH(self), maxcount
10274 );
10275 case PyUnicode_4BYTE_KIND:
10276 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010277 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 PyUnicode_GET_LENGTH(self), maxcount
10279 );
10280 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010281 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 }
10283
10284 if (PyUnicode_READY(substring) == -1)
10285 return NULL;
10286
10287 kind1 = PyUnicode_KIND(self);
10288 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 len1 = PyUnicode_GET_LENGTH(self);
10290 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010291 if (kind1 < kind2 || len1 < len2) {
10292 out = PyList_New(1);
10293 if (out == NULL)
10294 return NULL;
10295 Py_INCREF(self);
10296 PyList_SET_ITEM(out, 0, self);
10297 return out;
10298 }
10299 buf1 = PyUnicode_DATA(self);
10300 buf2 = PyUnicode_DATA(substring);
10301 if (kind2 != kind1) {
10302 buf2 = _PyUnicode_AsKind(substring, kind1);
10303 if (!buf2)
10304 return NULL;
10305 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010307 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010308 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010309 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10310 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010311 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010312 else
10313 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010314 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 break;
10316 case PyUnicode_2BYTE_KIND:
10317 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010318 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010319 break;
10320 case PyUnicode_4BYTE_KIND:
10321 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010322 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 break;
10324 default:
10325 out = NULL;
10326 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010327 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 PyMem_Free(buf2);
10329 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010330}
10331
Alexander Belopolsky40018472011-02-26 01:02:56 +000010332static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010333rsplit(PyObject *self,
10334 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010335 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010336{
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010337 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 void *buf1, *buf2;
10339 Py_ssize_t len1, len2;
10340 PyObject* out;
10341
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010342 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010343 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010344
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345 if (PyUnicode_READY(self) == -1)
10346 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010348 if (substring == NULL)
Benjamin Petersonead6b532011-12-20 17:23:42 -060010349 switch (PyUnicode_KIND(self)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010350 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010351 if (PyUnicode_IS_ASCII(self))
10352 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010353 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010354 PyUnicode_GET_LENGTH(self), maxcount
10355 );
10356 else
10357 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010358 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010359 PyUnicode_GET_LENGTH(self), maxcount
10360 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 case PyUnicode_2BYTE_KIND:
10362 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010363 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010364 PyUnicode_GET_LENGTH(self), maxcount
10365 );
10366 case PyUnicode_4BYTE_KIND:
10367 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010368 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 PyUnicode_GET_LENGTH(self), maxcount
10370 );
10371 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010372 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010373 }
10374
10375 if (PyUnicode_READY(substring) == -1)
10376 return NULL;
10377
10378 kind1 = PyUnicode_KIND(self);
10379 kind2 = PyUnicode_KIND(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 len1 = PyUnicode_GET_LENGTH(self);
10381 len2 = PyUnicode_GET_LENGTH(substring);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010382 if (kind1 < kind2 || len1 < len2) {
10383 out = PyList_New(1);
10384 if (out == NULL)
10385 return NULL;
10386 Py_INCREF(self);
10387 PyList_SET_ITEM(out, 0, self);
10388 return out;
10389 }
10390 buf1 = PyUnicode_DATA(self);
10391 buf2 = PyUnicode_DATA(substring);
10392 if (kind2 != kind1) {
10393 buf2 = _PyUnicode_AsKind(substring, kind1);
10394 if (!buf2)
10395 return NULL;
10396 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010398 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010400 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10401 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010402 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010403 else
10404 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010405 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010406 break;
10407 case PyUnicode_2BYTE_KIND:
10408 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010409 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010410 break;
10411 case PyUnicode_4BYTE_KIND:
10412 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010413 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 break;
10415 default:
10416 out = NULL;
10417 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010418 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010419 PyMem_Free(buf2);
10420 return out;
10421}
10422
10423static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010424anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10425 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010426{
Benjamin Petersonead6b532011-12-20 17:23:42 -060010427 switch (kind) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010429 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10430 return asciilib_find(buf1, len1, buf2, len2, offset);
10431 else
10432 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 case PyUnicode_2BYTE_KIND:
10434 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10435 case PyUnicode_4BYTE_KIND:
10436 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10437 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010438 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010439}
10440
10441static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010442anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10443 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444{
Benjamin Petersonc0b95d12011-12-20 17:24:05 -060010445 switch (kind) {
10446 case PyUnicode_1BYTE_KIND:
10447 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10448 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10449 else
10450 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
10451 case PyUnicode_2BYTE_KIND:
10452 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10453 case PyUnicode_4BYTE_KIND:
10454 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10455 }
Barry Warsawb2e57942017-09-14 18:13:16 -070010456 Py_UNREACHABLE();
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010457}
10458
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010459static void
10460replace_1char_inplace(PyObject *u, Py_ssize_t pos,
10461 Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
10462{
10463 int kind = PyUnicode_KIND(u);
10464 void *data = PyUnicode_DATA(u);
10465 Py_ssize_t len = PyUnicode_GET_LENGTH(u);
10466 if (kind == PyUnicode_1BYTE_KIND) {
10467 ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
10468 (Py_UCS1 *)data + len,
10469 u1, u2, maxcount);
10470 }
10471 else if (kind == PyUnicode_2BYTE_KIND) {
10472 ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
10473 (Py_UCS2 *)data + len,
10474 u1, u2, maxcount);
10475 }
10476 else {
10477 assert(kind == PyUnicode_4BYTE_KIND);
10478 ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
10479 (Py_UCS4 *)data + len,
10480 u1, u2, maxcount);
10481 }
10482}
10483
Alexander Belopolsky40018472011-02-26 01:02:56 +000010484static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010485replace(PyObject *self, PyObject *str1,
10486 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010488 PyObject *u;
10489 char *sbuf = PyUnicode_DATA(self);
10490 char *buf1 = PyUnicode_DATA(str1);
10491 char *buf2 = PyUnicode_DATA(str2);
10492 int srelease = 0, release1 = 0, release2 = 0;
10493 int skind = PyUnicode_KIND(self);
10494 int kind1 = PyUnicode_KIND(str1);
10495 int kind2 = PyUnicode_KIND(str2);
10496 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10497 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10498 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010499 int mayshrink;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010500 Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010501
10502 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010503 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010504 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010505 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010506
Victor Stinner59de0ee2011-10-07 10:01:28 +020010507 if (str1 == str2)
10508 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509
Victor Stinner49a0a212011-10-12 23:46:10 +020010510 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010511 maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
10512 if (maxchar < maxchar_str1)
10513 /* substring too wide to be present */
10514 goto nothing;
Victor Stinner49a0a212011-10-12 23:46:10 +020010515 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10516 /* Replacing str1 with str2 may cause a maxchar reduction in the
10517 result string. */
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010518 mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
Benjamin Peterson7e303732013-06-10 09:19:46 -070010519 maxchar = Py_MAX(maxchar, maxchar_str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 if (len1 == len2) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010522 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010523 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010524 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010525 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010526 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010527 Py_UCS4 u1, u2;
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010528 Py_ssize_t pos;
Victor Stinnerf6441102011-12-18 02:43:08 +010010529
Victor Stinner69ed0f42013-04-09 21:48:24 +020010530 u1 = PyUnicode_READ(kind1, buf1, 0);
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010531 pos = findchar(sbuf, skind, slen, u1, 1);
Victor Stinnerf6441102011-12-18 02:43:08 +010010532 if (pos < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010533 goto nothing;
Victor Stinner69ed0f42013-04-09 21:48:24 +020010534 u2 = PyUnicode_READ(kind2, buf2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010536 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 goto error;
Victor Stinnerf6441102011-12-18 02:43:08 +010010538
Serhiy Storchakae2cef882013-04-13 22:45:04 +030010539 _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
10540 replace_1char_inplace(u, pos, u1, u2, maxcount);
Victor Stinner49a0a212011-10-12 23:46:10 +020010541 }
10542 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010543 int rkind = skind;
10544 char *res;
Victor Stinnerf6441102011-12-18 02:43:08 +010010545 Py_ssize_t i;
Victor Stinner25a4b292011-10-06 12:31:55 +020010546
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 if (kind1 < rkind) {
10548 /* widen substring */
10549 buf1 = _PyUnicode_AsKind(str1, rkind);
10550 if (!buf1) goto error;
10551 release1 = 1;
10552 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010553 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010554 if (i < 0)
10555 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 if (rkind > kind2) {
10557 /* widen replacement */
10558 buf2 = _PyUnicode_AsKind(str2, rkind);
10559 if (!buf2) goto error;
10560 release2 = 1;
10561 }
10562 else if (rkind < kind2) {
10563 /* widen self and buf1 */
10564 rkind = kind2;
10565 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010566 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010567 sbuf = _PyUnicode_AsKind(self, rkind);
10568 if (!sbuf) goto error;
10569 srelease = 1;
10570 buf1 = _PyUnicode_AsKind(str1, rkind);
10571 if (!buf1) goto error;
10572 release1 = 1;
10573 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010574 u = PyUnicode_New(slen, maxchar);
10575 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010577 assert(PyUnicode_KIND(u) == rkind);
10578 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010579
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010580 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010581 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010582 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010584 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010586
10587 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010588 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010589 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010590 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010591 if (i == -1)
10592 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010593 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010594 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010595 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010597 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010598 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010599 }
10600 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 Py_ssize_t n, i, j, ires;
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010602 Py_ssize_t new_size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 int rkind = skind;
10604 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010606 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010607 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 buf1 = _PyUnicode_AsKind(str1, rkind);
10609 if (!buf1) goto error;
10610 release1 = 1;
10611 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010612 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010613 if (n == 0)
10614 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010616 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 buf2 = _PyUnicode_AsKind(str2, rkind);
10618 if (!buf2) goto error;
10619 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010620 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010621 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010622 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 rkind = kind2;
10624 sbuf = _PyUnicode_AsKind(self, rkind);
10625 if (!sbuf) goto error;
10626 srelease = 1;
10627 if (release1) PyMem_Free(buf1);
Antoine Pitrou6d5ad222012-11-17 23:28:17 +010010628 release1 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 buf1 = _PyUnicode_AsKind(str1, rkind);
10630 if (!buf1) goto error;
10631 release1 = 1;
10632 }
10633 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10634 PyUnicode_GET_LENGTH(str1))); */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020010635 if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010636 PyErr_SetString(PyExc_OverflowError,
10637 "replace string is too long");
10638 goto error;
10639 }
Mark Dickinsonc04ddff2012-10-06 18:04:49 +010010640 new_size = slen + n * (len2 - len1);
Victor Stinner49a0a212011-10-12 23:46:10 +020010641 if (new_size == 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020010642 _Py_INCREF_UNICODE_EMPTY();
10643 if (!unicode_empty)
10644 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010645 u = unicode_empty;
10646 goto done;
10647 }
Xiang Zhangb0541f42017-01-10 10:52:00 +080010648 if (new_size > (PY_SSIZE_T_MAX / rkind)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 PyErr_SetString(PyExc_OverflowError,
10650 "replace string is too long");
10651 goto error;
10652 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010653 u = PyUnicode_New(new_size, maxchar);
10654 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010656 assert(PyUnicode_KIND(u) == rkind);
10657 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 ires = i = 0;
10659 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010660 while (n-- > 0) {
10661 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010662 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010663 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010664 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010665 if (j == -1)
10666 break;
10667 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010668 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010669 memcpy(res + rkind * ires,
10670 sbuf + rkind * i,
10671 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010672 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010673 }
10674 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010675 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010676 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010677 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010678 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010679 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010680 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010681 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010682 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010684 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010685 memcpy(res + rkind * ires,
10686 sbuf + rkind * i,
10687 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010688 }
10689 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010690 /* interleave */
10691 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010692 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010694 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010695 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010696 if (--n <= 0)
10697 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010698 memcpy(res + rkind * ires,
10699 sbuf + rkind * i,
10700 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010701 ires++;
10702 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010703 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010704 memcpy(res + rkind * ires,
10705 sbuf + rkind * i,
10706 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010707 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010708 }
10709
10710 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010711 unicode_adjust_maxchar(&u);
10712 if (u == NULL)
10713 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010714 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010715
10716 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717 if (srelease)
10718 PyMem_FREE(sbuf);
10719 if (release1)
10720 PyMem_FREE(buf1);
10721 if (release2)
10722 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010723 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010724 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010725
Benjamin Peterson29060642009-01-31 22:14:21 +000010726 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010727 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010728 if (srelease)
10729 PyMem_FREE(sbuf);
10730 if (release1)
10731 PyMem_FREE(buf1);
10732 if (release2)
10733 PyMem_FREE(buf2);
Victor Stinnerc4b49542011-12-11 22:44:26 +010010734 return unicode_result_unchanged(self);
10735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010736 error:
10737 if (srelease && sbuf)
10738 PyMem_FREE(sbuf);
10739 if (release1 && buf1)
10740 PyMem_FREE(buf1);
10741 if (release2 && buf2)
10742 PyMem_FREE(buf2);
10743 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010744}
10745
10746/* --- Unicode Object Methods --------------------------------------------- */
10747
INADA Naoki3ae20562017-01-16 20:41:20 +090010748/*[clinic input]
10749str.title as unicode_title
Guido van Rossumd57fd912000-03-10 22:53:23 +000010750
INADA Naoki3ae20562017-01-16 20:41:20 +090010751Return a version of the string where each word is titlecased.
10752
10753More specifically, words start with uppercased characters and all remaining
10754cased characters have lower case.
10755[clinic start generated code]*/
10756
10757static PyObject *
10758unicode_title_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010759/*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760{
Benjamin Petersoneea48462012-01-16 14:28:50 -050010761 if (PyUnicode_READY(self) == -1)
10762 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010763 return case_operation(self, do_title);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010764}
10765
INADA Naoki3ae20562017-01-16 20:41:20 +090010766/*[clinic input]
10767str.capitalize as unicode_capitalize
Guido van Rossumd57fd912000-03-10 22:53:23 +000010768
INADA Naoki3ae20562017-01-16 20:41:20 +090010769Return a capitalized version of the string.
10770
10771More specifically, make the first character have upper case and the rest lower
10772case.
10773[clinic start generated code]*/
10774
10775static PyObject *
10776unicode_capitalize_impl(PyObject *self)
10777/*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010778{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050010779 if (PyUnicode_READY(self) == -1)
10780 return NULL;
10781 if (PyUnicode_GET_LENGTH(self) == 0)
10782 return unicode_result_unchanged(self);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010783 return case_operation(self, do_capitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010784}
10785
INADA Naoki3ae20562017-01-16 20:41:20 +090010786/*[clinic input]
10787str.casefold as unicode_casefold
10788
10789Return a version of the string suitable for caseless comparisons.
10790[clinic start generated code]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010791
10792static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010793unicode_casefold_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090010794/*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
Benjamin Petersond5890c82012-01-14 13:23:30 -050010795{
10796 if (PyUnicode_READY(self) == -1)
10797 return NULL;
10798 if (PyUnicode_IS_ASCII(self))
10799 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010010800 return case_operation(self, do_casefold);
Benjamin Petersond5890c82012-01-14 13:23:30 -050010801}
10802
10803
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010804/* Argument converter. Accepts a single Unicode character. */
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010805
10806static int
10807convert_uc(PyObject *obj, void *addr)
10808{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010810
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010811 if (!PyUnicode_Check(obj)) {
10812 PyErr_Format(PyExc_TypeError,
10813 "The fill character must be a unicode character, "
Victor Stinner998b8062018-09-12 00:23:25 +020010814 "not %.100s", Py_TYPE(obj)->tp_name);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010815 return 0;
10816 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010817 if (PyUnicode_READY(obj) < 0)
10818 return 0;
10819 if (PyUnicode_GET_LENGTH(obj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010820 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010821 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010822 return 0;
10823 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030010824 *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010825 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010826}
10827
INADA Naoki3ae20562017-01-16 20:41:20 +090010828/*[clinic input]
10829str.center as unicode_center
10830
10831 width: Py_ssize_t
10832 fillchar: Py_UCS4 = ' '
10833 /
10834
10835Return a centered string of length width.
10836
10837Padding is done using the specified fill character (default is a space).
10838[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010839
10840static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090010841unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
10842/*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010844 Py_ssize_t marg, left;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845
Benjamin Petersonbac79492012-01-14 13:34:47 -050010846 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847 return NULL;
10848
Victor Stinnerc4b49542011-12-11 22:44:26 +010010849 if (PyUnicode_GET_LENGTH(self) >= width)
10850 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851
Victor Stinnerc4b49542011-12-11 22:44:26 +010010852 marg = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010853 left = marg / 2 + (marg & width & 1);
10854
Victor Stinner9310abb2011-10-05 00:59:23 +020010855 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856}
10857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010858/* This function assumes that str1 and str2 are readied by the caller. */
10859
Marc-André Lemburge5034372000-08-08 08:04:29 +000010860static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010861unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010862{
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010863#define COMPARE(TYPE1, TYPE2) \
10864 do { \
10865 TYPE1* p1 = (TYPE1 *)data1; \
10866 TYPE2* p2 = (TYPE2 *)data2; \
10867 TYPE1* end = p1 + len; \
10868 Py_UCS4 c1, c2; \
10869 for (; p1 != end; p1++, p2++) { \
10870 c1 = *p1; \
10871 c2 = *p2; \
10872 if (c1 != c2) \
10873 return (c1 < c2) ? -1 : 1; \
10874 } \
10875 } \
10876 while (0)
10877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010878 int kind1, kind2;
10879 void *data1, *data2;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010880 Py_ssize_t len1, len2, len;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010881
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010882 kind1 = PyUnicode_KIND(str1);
10883 kind2 = PyUnicode_KIND(str2);
10884 data1 = PyUnicode_DATA(str1);
10885 data2 = PyUnicode_DATA(str2);
10886 len1 = PyUnicode_GET_LENGTH(str1);
10887 len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner770e19e2012-10-04 22:59:45 +020010888 len = Py_MIN(len1, len2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010889
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010890 switch(kind1) {
10891 case PyUnicode_1BYTE_KIND:
10892 {
10893 switch(kind2) {
10894 case PyUnicode_1BYTE_KIND:
10895 {
10896 int cmp = memcmp(data1, data2, len);
10897 /* normalize result of memcmp() into the range [-1; 1] */
10898 if (cmp < 0)
10899 return -1;
10900 if (cmp > 0)
10901 return 1;
10902 break;
Victor Stinner770e19e2012-10-04 22:59:45 +020010903 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010904 case PyUnicode_2BYTE_KIND:
10905 COMPARE(Py_UCS1, Py_UCS2);
10906 break;
10907 case PyUnicode_4BYTE_KIND:
10908 COMPARE(Py_UCS1, Py_UCS4);
10909 break;
10910 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010911 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010912 }
10913 break;
10914 }
10915 case PyUnicode_2BYTE_KIND:
10916 {
10917 switch(kind2) {
10918 case PyUnicode_1BYTE_KIND:
10919 COMPARE(Py_UCS2, Py_UCS1);
10920 break;
10921 case PyUnicode_2BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010922 {
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010923 COMPARE(Py_UCS2, Py_UCS2);
10924 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010925 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010926 case PyUnicode_4BYTE_KIND:
10927 COMPARE(Py_UCS2, Py_UCS4);
10928 break;
10929 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010930 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010931 }
10932 break;
10933 }
10934 case PyUnicode_4BYTE_KIND:
10935 {
10936 switch(kind2) {
10937 case PyUnicode_1BYTE_KIND:
10938 COMPARE(Py_UCS4, Py_UCS1);
10939 break;
10940 case PyUnicode_2BYTE_KIND:
10941 COMPARE(Py_UCS4, Py_UCS2);
10942 break;
10943 case PyUnicode_4BYTE_KIND:
Victor Stinnercd777ea2013-04-08 22:43:44 +020010944 {
10945#if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
10946 int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
10947 /* normalize result of wmemcmp() into the range [-1; 1] */
10948 if (cmp < 0)
10949 return -1;
10950 if (cmp > 0)
10951 return 1;
10952#else
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010953 COMPARE(Py_UCS4, Py_UCS4);
Victor Stinnercd777ea2013-04-08 22:43:44 +020010954#endif
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010955 break;
Victor Stinnercd777ea2013-04-08 22:43:44 +020010956 }
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010957 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010958 Py_UNREACHABLE();
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010959 }
10960 break;
10961 }
10962 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070010963 Py_UNREACHABLE();
Marc-André Lemburge5034372000-08-08 08:04:29 +000010964 }
10965
Victor Stinner770e19e2012-10-04 22:59:45 +020010966 if (len1 == len2)
10967 return 0;
10968 if (len1 < len2)
10969 return -1;
10970 else
10971 return 1;
Victor Stinnerc1302bb2013-04-08 21:50:54 +020010972
10973#undef COMPARE
Marc-André Lemburge5034372000-08-08 08:04:29 +000010974}
10975
Benjamin Peterson621b4302016-09-09 13:54:34 -070010976static int
Victor Stinnere5567ad2012-10-23 02:48:49 +020010977unicode_compare_eq(PyObject *str1, PyObject *str2)
10978{
10979 int kind;
10980 void *data1, *data2;
10981 Py_ssize_t len;
10982 int cmp;
10983
Victor Stinnere5567ad2012-10-23 02:48:49 +020010984 len = PyUnicode_GET_LENGTH(str1);
10985 if (PyUnicode_GET_LENGTH(str2) != len)
10986 return 0;
10987 kind = PyUnicode_KIND(str1);
10988 if (PyUnicode_KIND(str2) != kind)
10989 return 0;
10990 data1 = PyUnicode_DATA(str1);
10991 data2 = PyUnicode_DATA(str2);
10992
10993 cmp = memcmp(data1, data2, len * kind);
10994 return (cmp == 0);
10995}
10996
10997
Alexander Belopolsky40018472011-02-26 01:02:56 +000010998int
10999PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
11002 if (PyUnicode_READY(left) == -1 ||
11003 PyUnicode_READY(right) == -1)
11004 return -1;
Victor Stinnerf0c7b2a2013-11-04 11:27:14 +010011005
11006 /* a string is equal to itself */
11007 if (left == right)
11008 return 0;
11009
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011010 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011011 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000011012 PyErr_Format(PyExc_TypeError,
11013 "Can't compare %.100s and %.100s",
11014 left->ob_type->tp_name,
11015 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016 return -1;
11017}
11018
Martin v. Löwis5b222132007-06-10 09:51:05 +000011019int
11020PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
11021{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 Py_ssize_t i;
11023 int kind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011024 Py_UCS4 chr;
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011025 const unsigned char *ustr = (const unsigned char *)str;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011026
Victor Stinner910337b2011-10-03 03:20:16 +020011027 assert(_PyUnicode_CHECK(uni));
Serhiy Storchaka419967b2016-12-06 00:13:34 +020011028 if (!PyUnicode_IS_READY(uni)) {
11029 const wchar_t *ws = _PyUnicode_WSTR(uni);
11030 /* Compare Unicode string and source character set string */
11031 for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
11032 if (chr != ustr[i])
11033 return (chr < ustr[i]) ? -1 : 1;
11034 }
11035 /* This check keeps Python strings that end in '\0' from comparing equal
11036 to C strings identical up to that point. */
11037 if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
11038 return 1; /* uni is longer */
11039 if (ustr[i])
11040 return -1; /* str is longer */
11041 return 0;
11042 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 kind = PyUnicode_KIND(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011044 if (kind == PyUnicode_1BYTE_KIND) {
Victor Stinnera6b9b072013-10-30 18:27:13 +010011045 const void *data = PyUnicode_1BYTE_DATA(uni);
Victor Stinnere1b15922013-11-03 13:53:12 +010011046 size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
Victor Stinner602f7cf2013-10-29 23:31:50 +010011047 size_t len, len2 = strlen(str);
11048 int cmp;
11049
11050 len = Py_MIN(len1, len2);
11051 cmp = memcmp(data, str, len);
Victor Stinner21ea21e2013-11-04 11:28:26 +010011052 if (cmp != 0) {
11053 if (cmp < 0)
11054 return -1;
11055 else
11056 return 1;
11057 }
Victor Stinner602f7cf2013-10-29 23:31:50 +010011058 if (len1 > len2)
11059 return 1; /* uni is longer */
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011060 if (len1 < len2)
Victor Stinner602f7cf2013-10-29 23:31:50 +010011061 return -1; /* str is longer */
11062 return 0;
11063 }
11064 else {
11065 void *data = PyUnicode_DATA(uni);
11066 /* Compare Unicode string and source character set string */
11067 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
Victor Stinner12174a52014-08-15 23:17:38 +020011068 if (chr != (unsigned char)str[i])
Victor Stinner602f7cf2013-10-29 23:31:50 +010011069 return (chr < (unsigned char)(str[i])) ? -1 : 1;
11070 /* This check keeps Python strings that end in '\0' from comparing equal
11071 to C strings identical up to that point. */
11072 if (PyUnicode_GET_LENGTH(uni) != i || chr)
11073 return 1; /* uni is longer */
11074 if (str[i])
11075 return -1; /* str is longer */
11076 return 0;
11077 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000011078}
11079
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011080static int
11081non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
11082{
11083 size_t i, len;
11084 const wchar_t *p;
11085 len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
11086 if (strlen(str) != len)
11087 return 0;
11088 p = _PyUnicode_WSTR(unicode);
11089 assert(p);
11090 for (i = 0; i < len; i++) {
11091 unsigned char c = (unsigned char)str[i];
Serhiy Storchaka292dd1b2016-11-16 16:12:34 +020011092 if (c >= 128 || p[i] != (wchar_t)c)
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011093 return 0;
11094 }
11095 return 1;
11096}
11097
11098int
11099_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
11100{
11101 size_t len;
11102 assert(_PyUnicode_CHECK(unicode));
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011103 assert(str);
11104#ifndef NDEBUG
11105 for (const char *p = str; *p; p++) {
11106 assert((unsigned char)*p < 128);
11107 }
11108#endif
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +020011109 if (PyUnicode_READY(unicode) == -1) {
11110 /* Memory error or bad data */
11111 PyErr_Clear();
11112 return non_ready_unicode_equal_to_ascii_string(unicode, str);
11113 }
11114 if (!PyUnicode_IS_ASCII(unicode))
11115 return 0;
11116 len = (size_t)PyUnicode_GET_LENGTH(unicode);
11117 return strlen(str) == len &&
11118 memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
11119}
11120
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011121int
11122_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
11123{
11124 PyObject *right_uni;
11125 Py_hash_t hash;
11126
11127 assert(_PyUnicode_CHECK(left));
11128 assert(right->string);
Serhiy Storchakaa83a6a32016-11-16 20:02:44 +020011129#ifndef NDEBUG
11130 for (const char *p = right->string; *p; p++) {
11131 assert((unsigned char)*p < 128);
11132 }
11133#endif
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011134
11135 if (PyUnicode_READY(left) == -1) {
11136 /* memory error or bad data */
11137 PyErr_Clear();
11138 return non_ready_unicode_equal_to_ascii_string(left, right->string);
11139 }
11140
11141 if (!PyUnicode_IS_ASCII(left))
11142 return 0;
11143
11144 right_uni = _PyUnicode_FromId(right); /* borrowed */
11145 if (right_uni == NULL) {
11146 /* memory error or bad data */
11147 PyErr_Clear();
11148 return _PyUnicode_EqualToASCIIString(left, right->string);
11149 }
11150
11151 if (left == right_uni)
11152 return 1;
11153
11154 if (PyUnicode_CHECK_INTERNED(left))
11155 return 0;
11156
INADA Naoki7cc95f52018-01-28 02:07:09 +090011157 assert(_PyUnicode_HASH(right_uni) != -1);
Serhiy Storchakaf5894dd2016-11-16 15:40:39 +020011158 hash = _PyUnicode_HASH(left);
11159 if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
11160 return 0;
11161
11162 return unicode_compare_eq(left, right_uni);
11163}
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000011164
Alexander Belopolsky40018472011-02-26 01:02:56 +000011165PyObject *
11166PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011167{
11168 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011169
Victor Stinnere5567ad2012-10-23 02:48:49 +020011170 if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
11171 Py_RETURN_NOTIMPLEMENTED;
11172
11173 if (PyUnicode_READY(left) == -1 ||
11174 PyUnicode_READY(right) == -1)
11175 return NULL;
11176
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011177 if (left == right) {
11178 switch (op) {
11179 case Py_EQ:
11180 case Py_LE:
11181 case Py_GE:
11182 /* a string is equal to itself */
stratakise8b19652017-11-02 11:32:54 +010011183 Py_RETURN_TRUE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011184 case Py_NE:
11185 case Py_LT:
11186 case Py_GT:
stratakise8b19652017-11-02 11:32:54 +010011187 Py_RETURN_FALSE;
Victor Stinnerfd9e44d2013-11-04 11:23:05 +010011188 default:
11189 PyErr_BadArgument();
11190 return NULL;
11191 }
11192 }
11193 else if (op == Py_EQ || op == Py_NE) {
Victor Stinnere5567ad2012-10-23 02:48:49 +020011194 result = unicode_compare_eq(left, right);
Victor Stinnerc8bc5372013-11-04 11:08:10 +010011195 result ^= (op == Py_NE);
stratakise8b19652017-11-02 11:32:54 +010011196 return PyBool_FromLong(result);
Victor Stinnere5567ad2012-10-23 02:48:49 +020011197 }
11198 else {
Victor Stinner90db9c42012-10-04 21:53:50 +020011199 result = unicode_compare(left, right);
stratakise8b19652017-11-02 11:32:54 +010011200 Py_RETURN_RICHCOMPARE(result, 0, op);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011201 }
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000011202}
11203
Alexander Belopolsky40018472011-02-26 01:02:56 +000011204int
Raymond Hettingerac2ef652015-07-04 16:04:44 -070011205_PyUnicode_EQ(PyObject *aa, PyObject *bb)
11206{
11207 return unicode_eq(aa, bb);
11208}
11209
11210int
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011211PyUnicode_Contains(PyObject *str, PyObject *substr)
Guido van Rossum403d68b2000-03-13 15:55:09 +000011212{
Victor Stinner77282cb2013-04-14 19:22:47 +020011213 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 void *buf1, *buf2;
11215 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011216 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011217
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011218 if (!PyUnicode_Check(substr)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011219 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020011220 "'in <string>' requires string as left operand, not %.100s",
11221 Py_TYPE(substr)->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011222 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011223 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011224 if (PyUnicode_READY(substr) == -1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000011225 return -1;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011226 if (ensure_unicode(str) < 0)
11227 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011228
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011229 kind1 = PyUnicode_KIND(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011230 kind2 = PyUnicode_KIND(substr);
11231 if (kind1 < kind2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011232 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011233 len1 = PyUnicode_GET_LENGTH(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011234 len2 = PyUnicode_GET_LENGTH(substr);
11235 if (len1 < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011236 return 0;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011237 buf1 = PyUnicode_DATA(str);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011238 buf2 = PyUnicode_DATA(substr);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011239 if (len2 == 1) {
11240 Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
11241 result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011242 return result;
11243 }
11244 if (kind2 != kind1) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011245 buf2 = _PyUnicode_AsKind(substr, kind1);
11246 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011247 return -1;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011249
Victor Stinner77282cb2013-04-14 19:22:47 +020011250 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 case PyUnicode_1BYTE_KIND:
11252 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
11253 break;
11254 case PyUnicode_2BYTE_KIND:
11255 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
11256 break;
11257 case PyUnicode_4BYTE_KIND:
11258 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
11259 break;
11260 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011261 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011262 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011263
Victor Stinner77282cb2013-04-14 19:22:47 +020011264 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011265 PyMem_Free(buf2);
11266
Guido van Rossum403d68b2000-03-13 15:55:09 +000011267 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000011268}
11269
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270/* Concat to string or Unicode object giving a new Unicode object. */
11271
Alexander Belopolsky40018472011-02-26 01:02:56 +000011272PyObject *
11273PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011274{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011275 PyObject *result;
Victor Stinner127226b2011-10-13 01:12:34 +020011276 Py_UCS4 maxchar, maxchar2;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011277 Py_ssize_t left_len, right_len, new_len;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278
Serhiy Storchaka004e03f2017-03-19 19:38:42 +020011279 if (ensure_unicode(left) < 0)
11280 return NULL;
11281
11282 if (!PyUnicode_Check(right)) {
11283 PyErr_Format(PyExc_TypeError,
11284 "can only concatenate str (not \"%.200s\") to str",
11285 right->ob_type->tp_name);
11286 return NULL;
11287 }
11288 if (PyUnicode_READY(right) < 0)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011289 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011290
11291 /* Shortcuts */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011292 if (left == unicode_empty)
11293 return PyUnicode_FromObject(right);
11294 if (right == unicode_empty)
11295 return PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011297 left_len = PyUnicode_GET_LENGTH(left);
11298 right_len = PyUnicode_GET_LENGTH(right);
11299 if (left_len > PY_SSIZE_T_MAX - right_len) {
Victor Stinner488fa492011-12-12 00:01:39 +010011300 PyErr_SetString(PyExc_OverflowError,
11301 "strings are too large to concat");
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011302 return NULL;
Victor Stinner488fa492011-12-12 00:01:39 +010011303 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011304 new_len = left_len + right_len;
Victor Stinner488fa492011-12-12 00:01:39 +010011305
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011306 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11307 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011308 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309
Guido van Rossumd57fd912000-03-10 22:53:23 +000011310 /* Concat the two Unicode strings */
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011311 result = PyUnicode_New(new_len, maxchar);
11312 if (result == NULL)
11313 return NULL;
11314 _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
11315 _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
11316 assert(_PyUnicode_CheckConsistency(result, 1));
11317 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318}
11319
Walter Dörwald1ab83302007-05-18 17:15:44 +000011320void
Victor Stinner23e56682011-10-03 03:54:37 +020011321PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000011322{
Victor Stinner23e56682011-10-03 03:54:37 +020011323 PyObject *left, *res;
Victor Stinner488fa492011-12-12 00:01:39 +010011324 Py_UCS4 maxchar, maxchar2;
11325 Py_ssize_t left_len, right_len, new_len;
Victor Stinner23e56682011-10-03 03:54:37 +020011326
11327 if (p_left == NULL) {
11328 if (!PyErr_Occurred())
11329 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000011330 return;
11331 }
Victor Stinner23e56682011-10-03 03:54:37 +020011332 left = *p_left;
Victor Stinnerf0335102013-04-14 19:13:03 +020011333 if (right == NULL || left == NULL
11334 || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
Victor Stinner23e56682011-10-03 03:54:37 +020011335 if (!PyErr_Occurred())
11336 PyErr_BadInternalCall();
11337 goto error;
11338 }
11339
Benjamin Petersonbac79492012-01-14 13:34:47 -050011340 if (PyUnicode_READY(left) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011341 goto error;
Benjamin Petersonbac79492012-01-14 13:34:47 -050011342 if (PyUnicode_READY(right) == -1)
Victor Stinnere1335c72011-10-04 20:53:03 +020011343 goto error;
11344
Victor Stinner488fa492011-12-12 00:01:39 +010011345 /* Shortcuts */
11346 if (left == unicode_empty) {
11347 Py_DECREF(left);
11348 Py_INCREF(right);
11349 *p_left = right;
11350 return;
11351 }
11352 if (right == unicode_empty)
11353 return;
11354
11355 left_len = PyUnicode_GET_LENGTH(left);
11356 right_len = PyUnicode_GET_LENGTH(right);
11357 if (left_len > PY_SSIZE_T_MAX - right_len) {
11358 PyErr_SetString(PyExc_OverflowError,
11359 "strings are too large to concat");
11360 goto error;
11361 }
11362 new_len = left_len + right_len;
11363
11364 if (unicode_modifiable(left)
11365 && PyUnicode_CheckExact(right)
11366 && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
Victor Stinnerb0923652011-10-04 01:17:31 +020011367 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
11368 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020011369 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020011370 not so different than duplicating the string. */
Victor Stinner488fa492011-12-12 00:01:39 +010011371 && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
11372 {
11373 /* append inplace */
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011374 if (unicode_resize(p_left, new_len) != 0)
Victor Stinner488fa492011-12-12 00:01:39 +010011375 goto error;
Victor Stinnerf0335102013-04-14 19:13:03 +020011376
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011377 /* copy 'right' into the newly allocated area of 'left' */
11378 _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
Victor Stinner23e56682011-10-03 03:54:37 +020011379 }
Victor Stinner488fa492011-12-12 00:01:39 +010011380 else {
11381 maxchar = PyUnicode_MAX_CHAR_VALUE(left);
11382 maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
Benjamin Peterson7e303732013-06-10 09:19:46 -070011383 maxchar = Py_MAX(maxchar, maxchar2);
Victor Stinner23e56682011-10-03 03:54:37 +020011384
Victor Stinner488fa492011-12-12 00:01:39 +010011385 /* Concat the two Unicode strings */
11386 res = PyUnicode_New(new_len, maxchar);
11387 if (res == NULL)
11388 goto error;
Victor Stinnerd3f08822012-05-29 12:57:52 +020011389 _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
11390 _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
Victor Stinner488fa492011-12-12 00:01:39 +010011391 Py_DECREF(left);
Victor Stinnerbb4503f2013-04-18 09:41:34 +020011392 *p_left = res;
Victor Stinner488fa492011-12-12 00:01:39 +010011393 }
11394 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020011395 return;
11396
11397error:
Victor Stinner488fa492011-12-12 00:01:39 +010011398 Py_CLEAR(*p_left);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011399}
11400
11401void
11402PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
11403{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011404 PyUnicode_Append(pleft, right);
11405 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000011406}
11407
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011408/*
11409Wraps stringlib_parse_args_finds() and additionally ensures that the
11410first argument is a unicode object.
11411*/
11412
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070011413static inline int
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011414parse_args_finds_unicode(const char * function_name, PyObject *args,
11415 PyObject **substring,
11416 Py_ssize_t *start, Py_ssize_t *end)
11417{
11418 if(stringlib_parse_args_finds(function_name, args, substring,
11419 start, end)) {
11420 if (ensure_unicode(*substring) < 0)
11421 return 0;
11422 return 1;
11423 }
11424 return 0;
11425}
11426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011427PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000011430Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011431string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011432interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011433
11434static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011435unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011437 PyObject *substring = NULL; /* initialize to fix a compiler warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011438 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011439 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440 PyObject *result;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011441 int kind1, kind2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 void *buf1, *buf2;
11443 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011444
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011445 if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000011447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011448 kind1 = PyUnicode_KIND(self);
11449 kind2 = PyUnicode_KIND(substring);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011450 if (kind1 < kind2)
Benjamin Petersonb63f49f2012-05-03 18:31:07 -040011451 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 len1 = PyUnicode_GET_LENGTH(self);
11454 len2 = PyUnicode_GET_LENGTH(substring);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011455 ADJUST_INDICES(start, end, len1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011456 if (end - start < len2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011457 return PyLong_FromLong(0);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011458
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011459 buf1 = PyUnicode_DATA(self);
11460 buf2 = PyUnicode_DATA(substring);
11461 if (kind2 != kind1) {
11462 buf2 = _PyUnicode_AsKind(substring, kind1);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011463 if (!buf2)
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011464 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011465 }
11466 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011467 case PyUnicode_1BYTE_KIND:
11468 iresult = ucs1lib_count(
11469 ((Py_UCS1*)buf1) + start, end - start,
11470 buf2, len2, PY_SSIZE_T_MAX
11471 );
11472 break;
11473 case PyUnicode_2BYTE_KIND:
11474 iresult = ucs2lib_count(
11475 ((Py_UCS2*)buf1) + start, end - start,
11476 buf2, len2, PY_SSIZE_T_MAX
11477 );
11478 break;
11479 case PyUnicode_4BYTE_KIND:
11480 iresult = ucs4lib_count(
11481 ((Py_UCS4*)buf1) + start, end - start,
11482 buf2, len2, PY_SSIZE_T_MAX
11483 );
11484 break;
11485 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070011486 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011487 }
11488
11489 result = PyLong_FromSsize_t(iresult);
11490
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020011491 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011492 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011493
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494 return result;
11495}
11496
INADA Naoki3ae20562017-01-16 20:41:20 +090011497/*[clinic input]
11498str.encode as unicode_encode
11499
11500 encoding: str(c_default="NULL") = 'utf-8'
11501 The encoding in which to encode the string.
11502 errors: str(c_default="NULL") = 'strict'
11503 The error handling scheme to use for encoding errors.
11504 The default is 'strict' meaning that encoding errors raise a
11505 UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
11506 'xmlcharrefreplace' as well as any other name registered with
11507 codecs.register_error that can handle UnicodeEncodeErrors.
11508
11509Encode the string using the codec registered for encoding.
11510[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511
11512static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090011513unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
INADA Naoki15f94592017-01-16 21:49:13 +090011514/*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011515{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011516 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011517}
11518
INADA Naoki3ae20562017-01-16 20:41:20 +090011519/*[clinic input]
11520str.expandtabs as unicode_expandtabs
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521
INADA Naoki3ae20562017-01-16 20:41:20 +090011522 tabsize: int = 8
11523
11524Return a copy where all tab characters are expanded using spaces.
11525
11526If tabsize is not given, a tab size of 8 characters is assumed.
11527[clinic start generated code]*/
11528
11529static PyObject *
11530unicode_expandtabs_impl(PyObject *self, int tabsize)
11531/*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011533 Py_ssize_t i, j, line_pos, src_len, incr;
11534 Py_UCS4 ch;
11535 PyObject *u;
11536 void *src_data, *dest_data;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011537 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011538 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539
Antoine Pitrou22425222011-10-04 19:10:51 +020011540 if (PyUnicode_READY(self) == -1)
11541 return NULL;
11542
Thomas Wouters7e474022000-07-16 12:04:32 +000011543 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011544 src_len = PyUnicode_GET_LENGTH(self);
11545 i = j = line_pos = 0;
11546 kind = PyUnicode_KIND(self);
11547 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011548 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011549 for (; i < src_len; i++) {
11550 ch = PyUnicode_READ(kind, src_data, i);
11551 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011552 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011553 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011554 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011555 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011556 goto overflow;
11557 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011559 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011560 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011561 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011562 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011563 goto overflow;
11564 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011566 if (ch == '\n' || ch == '\r')
11567 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011569 }
Victor Stinnerc4b49542011-12-11 22:44:26 +010011570 if (!found)
11571 return unicode_result_unchanged(self);
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011572
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011574 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575 if (!u)
11576 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011577 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578
Antoine Pitroue71d5742011-10-04 15:55:09 +020011579 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580
Antoine Pitroue71d5742011-10-04 15:55:09 +020011581 for (; i < src_len; i++) {
11582 ch = PyUnicode_READ(kind, src_data, i);
11583 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011584 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011585 incr = tabsize - (line_pos % tabsize);
11586 line_pos += incr;
Victor Stinner59423e32018-11-26 13:40:01 +010011587 unicode_fill(kind, dest_data, ' ', j, incr);
Victor Stinnerda79e632012-02-22 13:37:04 +010011588 j += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011589 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011590 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011591 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011592 line_pos++;
11593 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011594 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011595 if (ch == '\n' || ch == '\r')
11596 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011598 }
11599 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinnerd3df8ab2011-11-22 01:22:34 +010011600 return unicode_result(u);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011601
Antoine Pitroue71d5742011-10-04 15:55:09 +020011602 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011603 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11604 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605}
11606
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011607PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011608 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609\n\
11610Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011611such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612arguments start and end are interpreted as in slice notation.\n\
11613\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011614Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615
11616static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011617unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011619 /* initialize variables to prevent gcc warning */
11620 PyObject *substring = NULL;
11621 Py_ssize_t start = 0;
11622 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011623 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011625 if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011628 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011629 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011631 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011632
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 if (result == -2)
11634 return NULL;
11635
Christian Heimes217cfd12007-12-02 14:31:20 +000011636 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011637}
11638
11639static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011640unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641{
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011642 void *data;
11643 enum PyUnicode_Kind kind;
11644 Py_UCS4 ch;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011645
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011646 if (!PyUnicode_Check(self)) {
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011647 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 return NULL;
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011649 }
Serhiy Storchakae3b2b4b2017-09-08 09:58:51 +030011650 if (PyUnicode_READY(self) == -1) {
11651 return NULL;
11652 }
Victor Stinnerb6cd0142012-05-03 02:17:04 +020011653 if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
11654 PyErr_SetString(PyExc_IndexError, "string index out of range");
11655 return NULL;
11656 }
11657 kind = PyUnicode_KIND(self);
11658 data = PyUnicode_DATA(self);
11659 ch = PyUnicode_READ(kind, data, index);
Victor Stinner985a82a2014-01-03 12:53:47 +010011660 return unicode_char(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011661}
11662
Guido van Rossumc2504932007-09-18 19:42:40 +000011663/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011664 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011665static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011666unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011667{
Guido van Rossumc2504932007-09-18 19:42:40 +000011668 Py_ssize_t len;
Gregory P. Smith27cbcd62012-12-10 18:15:46 -080011669 Py_uhash_t x; /* Unsigned for defined overflow behavior. */
Guido van Rossumc2504932007-09-18 19:42:40 +000011670
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011671#ifdef Py_DEBUG
Benjamin Peterson69e97272012-02-21 11:08:50 -050011672 assert(_Py_HashSecret_Initialized);
Benjamin Petersonf6622c82012-04-09 14:53:07 -040011673#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 if (_PyUnicode_HASH(self) != -1)
11675 return _PyUnicode_HASH(self);
11676 if (PyUnicode_READY(self) == -1)
11677 return -1;
11678 len = PyUnicode_GET_LENGTH(self);
Georg Brandl16fa2a12012-02-21 00:50:13 +010011679 /*
11680 We make the hash of the empty string be 0, rather than using
11681 (prefix ^ suffix), since this slightly obfuscates the hash secret
11682 */
11683 if (len == 0) {
11684 _PyUnicode_HASH(self) = 0;
11685 return 0;
11686 }
Christian Heimes985ecdc2013-11-20 11:46:18 +010011687 x = _Py_HashBytes(PyUnicode_DATA(self),
11688 PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011689 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011690 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691}
11692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011693PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011694 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695\n\
oldkaa0735f2018-02-02 16:52:55 +080011696Return the lowest index in S where substring sub is found,\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070011697such that sub is contained within S[start:end]. Optional\n\
11698arguments start and end are interpreted as in slice notation.\n\
11699\n\
11700Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701
11702static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011703unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011705 /* initialize variables to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +000011706 Py_ssize_t result;
Victor Stinner0c39b1b2015-03-18 15:02:06 +010011707 PyObject *substring = NULL;
11708 Py_ssize_t start = 0;
11709 Py_ssize_t end = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030011711 if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011713
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011714 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011715 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011716
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030011717 result = any_find_slice(self, substring, start, end, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011718
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011719 if (result == -2)
11720 return NULL;
11721
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722 if (result < 0) {
11723 PyErr_SetString(PyExc_ValueError, "substring not found");
11724 return NULL;
11725 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011726
Christian Heimes217cfd12007-12-02 14:31:20 +000011727 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728}
11729
INADA Naoki3ae20562017-01-16 20:41:20 +090011730/*[clinic input]
INADA Naokia49ac992018-01-27 14:06:21 +090011731str.isascii as unicode_isascii
11732
11733Return True if all characters in the string are ASCII, False otherwise.
11734
11735ASCII characters have code points in the range U+0000-U+007F.
11736Empty string is ASCII too.
11737[clinic start generated code]*/
11738
11739static PyObject *
11740unicode_isascii_impl(PyObject *self)
11741/*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
11742{
11743 if (PyUnicode_READY(self) == -1) {
11744 return NULL;
11745 }
11746 return PyBool_FromLong(PyUnicode_IS_ASCII(self));
11747}
11748
11749/*[clinic input]
INADA Naoki3ae20562017-01-16 20:41:20 +090011750str.islower as unicode_islower
Guido van Rossumd57fd912000-03-10 22:53:23 +000011751
INADA Naoki3ae20562017-01-16 20:41:20 +090011752Return True if the string is a lowercase string, False otherwise.
11753
11754A string is lowercase if all cased characters in the string are lowercase and
11755there is at least one cased character in the string.
11756[clinic start generated code]*/
11757
11758static PyObject *
11759unicode_islower_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011760/*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011761{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 Py_ssize_t i, length;
11763 int kind;
11764 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011765 int cased;
11766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 if (PyUnicode_READY(self) == -1)
11768 return NULL;
11769 length = PyUnicode_GET_LENGTH(self);
11770 kind = PyUnicode_KIND(self);
11771 data = PyUnicode_DATA(self);
11772
Guido van Rossumd57fd912000-03-10 22:53:23 +000011773 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011774 if (length == 1)
11775 return PyBool_FromLong(
11776 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011777
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011778 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011780 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011781
Guido van Rossumd57fd912000-03-10 22:53:23 +000011782 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011783 for (i = 0; i < length; i++) {
11784 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011785
Benjamin Peterson29060642009-01-31 22:14:21 +000011786 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011787 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011788 else if (!cased && Py_UNICODE_ISLOWER(ch))
11789 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011790 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011791 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011792}
11793
INADA Naoki3ae20562017-01-16 20:41:20 +090011794/*[clinic input]
11795str.isupper as unicode_isupper
Guido van Rossumd57fd912000-03-10 22:53:23 +000011796
INADA Naoki3ae20562017-01-16 20:41:20 +090011797Return True if the string is an uppercase string, False otherwise.
11798
11799A string is uppercase if all cased characters in the string are uppercase and
11800there is at least one cased character in the string.
11801[clinic start generated code]*/
11802
11803static PyObject *
11804unicode_isupper_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011805/*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011806{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011807 Py_ssize_t i, length;
11808 int kind;
11809 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810 int cased;
11811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011812 if (PyUnicode_READY(self) == -1)
11813 return NULL;
11814 length = PyUnicode_GET_LENGTH(self);
11815 kind = PyUnicode_KIND(self);
11816 data = PyUnicode_DATA(self);
11817
Guido van Rossumd57fd912000-03-10 22:53:23 +000011818 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819 if (length == 1)
11820 return PyBool_FromLong(
11821 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011823 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011824 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011825 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011826
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011828 for (i = 0; i < length; i++) {
11829 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011830
Benjamin Peterson29060642009-01-31 22:14:21 +000011831 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011832 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011833 else if (!cased && Py_UNICODE_ISUPPER(ch))
11834 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011835 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011836 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837}
11838
INADA Naoki3ae20562017-01-16 20:41:20 +090011839/*[clinic input]
11840str.istitle as unicode_istitle
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841
INADA Naoki3ae20562017-01-16 20:41:20 +090011842Return True if the string is a title-cased string, False otherwise.
11843
11844In a title-cased string, upper- and title-case characters may only
11845follow uncased characters and lowercase characters only cased ones.
11846[clinic start generated code]*/
11847
11848static PyObject *
11849unicode_istitle_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011850/*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011851{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011852 Py_ssize_t i, length;
11853 int kind;
11854 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855 int cased, previous_is_cased;
11856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 if (PyUnicode_READY(self) == -1)
11858 return NULL;
11859 length = PyUnicode_GET_LENGTH(self);
11860 kind = PyUnicode_KIND(self);
11861 data = PyUnicode_DATA(self);
11862
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 if (length == 1) {
11865 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11866 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11867 (Py_UNICODE_ISUPPER(ch) != 0));
11868 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011870 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011871 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011872 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011873
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874 cased = 0;
11875 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011876 for (i = 0; i < length; i++) {
11877 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011878
Benjamin Peterson29060642009-01-31 22:14:21 +000011879 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11880 if (previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011881 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011882 previous_is_cased = 1;
11883 cased = 1;
11884 }
11885 else if (Py_UNICODE_ISLOWER(ch)) {
11886 if (!previous_is_cased)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011887 Py_RETURN_FALSE;
Benjamin Peterson29060642009-01-31 22:14:21 +000011888 previous_is_cased = 1;
11889 cased = 1;
11890 }
11891 else
11892 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011893 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011894 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895}
11896
INADA Naoki3ae20562017-01-16 20:41:20 +090011897/*[clinic input]
11898str.isspace as unicode_isspace
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899
INADA Naoki3ae20562017-01-16 20:41:20 +090011900Return True if the string is a whitespace string, False otherwise.
11901
11902A string is whitespace if all characters in the string are whitespace and there
11903is at least one character in the string.
11904[clinic start generated code]*/
11905
11906static PyObject *
11907unicode_isspace_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011908/*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 Py_ssize_t i, length;
11911 int kind;
11912 void *data;
11913
11914 if (PyUnicode_READY(self) == -1)
11915 return NULL;
11916 length = PyUnicode_GET_LENGTH(self);
11917 kind = PyUnicode_KIND(self);
11918 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011919
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011921 if (length == 1)
11922 return PyBool_FromLong(
11923 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011925 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011927 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011928
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011929 for (i = 0; i < length; i++) {
11930 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011931 if (!Py_UNICODE_ISSPACE(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011932 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011934 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011935}
11936
INADA Naoki3ae20562017-01-16 20:41:20 +090011937/*[clinic input]
11938str.isalpha as unicode_isalpha
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011939
INADA Naoki3ae20562017-01-16 20:41:20 +090011940Return True if the string is an alphabetic string, False otherwise.
11941
11942A string is alphabetic if all characters in the string are alphabetic and there
11943is at least one character in the string.
11944[clinic start generated code]*/
11945
11946static PyObject *
11947unicode_isalpha_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011948/*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011949{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011950 Py_ssize_t i, length;
11951 int kind;
11952 void *data;
11953
11954 if (PyUnicode_READY(self) == -1)
11955 return NULL;
11956 length = PyUnicode_GET_LENGTH(self);
11957 kind = PyUnicode_KIND(self);
11958 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011959
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011960 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 if (length == 1)
11962 return PyBool_FromLong(
11963 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011964
11965 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011967 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 for (i = 0; i < length; i++) {
11970 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011971 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011972 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020011973 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011974}
11975
INADA Naoki3ae20562017-01-16 20:41:20 +090011976/*[clinic input]
11977str.isalnum as unicode_isalnum
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011978
INADA Naoki3ae20562017-01-16 20:41:20 +090011979Return True if the string is an alpha-numeric string, False otherwise.
11980
11981A string is alpha-numeric if all characters in the string are alpha-numeric and
11982there is at least one character in the string.
11983[clinic start generated code]*/
11984
11985static PyObject *
11986unicode_isalnum_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090011987/*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011988{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011989 int kind;
11990 void *data;
11991 Py_ssize_t len, i;
11992
11993 if (PyUnicode_READY(self) == -1)
11994 return NULL;
11995
11996 kind = PyUnicode_KIND(self);
11997 data = PyUnicode_DATA(self);
11998 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011999
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012000 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 if (len == 1) {
12002 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12003 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
12004 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012005
12006 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 if (len == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012008 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012010 for (i = 0; i < len; i++) {
12011 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012012 if (!Py_UNICODE_ISALNUM(ch))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012013 Py_RETURN_FALSE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012014 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012015 Py_RETURN_TRUE;
Marc-André Lemburga7acf422000-07-05 09:49:44 +000012016}
12017
INADA Naoki3ae20562017-01-16 20:41:20 +090012018/*[clinic input]
12019str.isdecimal as unicode_isdecimal
Guido van Rossumd57fd912000-03-10 22:53:23 +000012020
INADA Naoki3ae20562017-01-16 20:41:20 +090012021Return True if the string is a decimal string, False otherwise.
12022
12023A string is a decimal string if all characters in the string are decimal and
12024there is at least one character in the string.
12025[clinic start generated code]*/
12026
12027static PyObject *
12028unicode_isdecimal_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012029/*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012031 Py_ssize_t i, length;
12032 int kind;
12033 void *data;
12034
12035 if (PyUnicode_READY(self) == -1)
12036 return NULL;
12037 length = PyUnicode_GET_LENGTH(self);
12038 kind = PyUnicode_KIND(self);
12039 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012040
Guido van Rossumd57fd912000-03-10 22:53:23 +000012041 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012042 if (length == 1)
12043 return PyBool_FromLong(
12044 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012045
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012046 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012048 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 for (i = 0; i < length; i++) {
12051 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012052 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012053 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012054 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012055}
12056
INADA Naoki3ae20562017-01-16 20:41:20 +090012057/*[clinic input]
12058str.isdigit as unicode_isdigit
Guido van Rossumd57fd912000-03-10 22:53:23 +000012059
INADA Naoki3ae20562017-01-16 20:41:20 +090012060Return True if the string is a digit string, False otherwise.
12061
12062A string is a digit string if all characters in the string are digits and there
12063is at least one character in the string.
12064[clinic start generated code]*/
12065
12066static PyObject *
12067unicode_isdigit_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012068/*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012070 Py_ssize_t i, length;
12071 int kind;
12072 void *data;
12073
12074 if (PyUnicode_READY(self) == -1)
12075 return NULL;
12076 length = PyUnicode_GET_LENGTH(self);
12077 kind = PyUnicode_KIND(self);
12078 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012079
Guido van Rossumd57fd912000-03-10 22:53:23 +000012080 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 if (length == 1) {
12082 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
12083 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
12084 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012085
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012086 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012087 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012088 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012090 for (i = 0; i < length; i++) {
12091 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012092 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012094 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095}
12096
INADA Naoki3ae20562017-01-16 20:41:20 +090012097/*[clinic input]
12098str.isnumeric as unicode_isnumeric
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099
INADA Naoki3ae20562017-01-16 20:41:20 +090012100Return True if the string is a numeric string, False otherwise.
12101
12102A string is numeric if all characters in the string are numeric and there is at
12103least one character in the string.
12104[clinic start generated code]*/
12105
12106static PyObject *
12107unicode_isnumeric_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012108/*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012110 Py_ssize_t i, length;
12111 int kind;
12112 void *data;
12113
12114 if (PyUnicode_READY(self) == -1)
12115 return NULL;
12116 length = PyUnicode_GET_LENGTH(self);
12117 kind = PyUnicode_KIND(self);
12118 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121 if (length == 1)
12122 return PyBool_FromLong(
12123 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012125 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012126 if (length == 0)
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012127 Py_RETURN_FALSE;
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000012128
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012129 for (i = 0; i < length; i++) {
12130 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012131 Py_RETURN_FALSE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132 }
Serhiy Storchaka370fd202017-03-08 20:47:48 +020012133 Py_RETURN_TRUE;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134}
12135
Martin v. Löwis47383402007-08-15 07:32:56 +000012136int
12137PyUnicode_IsIdentifier(PyObject *self)
12138{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 int kind;
12140 void *data;
12141 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030012142 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000012143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 if (PyUnicode_READY(self) == -1) {
12145 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000012146 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 }
12148
12149 /* Special case for empty strings */
12150 if (PyUnicode_GET_LENGTH(self) == 0)
12151 return 0;
12152 kind = PyUnicode_KIND(self);
12153 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000012154
12155 /* PEP 3131 says that the first character must be in
12156 XID_Start and subsequent characters in XID_Continue,
12157 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000012158 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000012159 letters, digits, underscore). However, given the current
12160 definition of XID_Start and XID_Continue, it is sufficient
12161 to check just for these, except that _ must be allowed
12162 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050012164 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000012165 return 0;
12166
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040012167 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000012169 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000012170 return 1;
12171}
12172
INADA Naoki3ae20562017-01-16 20:41:20 +090012173/*[clinic input]
12174str.isidentifier as unicode_isidentifier
Martin v. Löwis47383402007-08-15 07:32:56 +000012175
INADA Naoki3ae20562017-01-16 20:41:20 +090012176Return True if the string is a valid Python identifier, False otherwise.
12177
Sanyam Khuranaffc5a142018-10-08 12:23:32 +053012178Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012179such as "def" or "class".
INADA Naoki3ae20562017-01-16 20:41:20 +090012180[clinic start generated code]*/
12181
12182static PyObject *
12183unicode_isidentifier_impl(PyObject *self)
Emanuele Gaifasfc8205c2018-10-08 12:44:47 +020012184/*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
Martin v. Löwis47383402007-08-15 07:32:56 +000012185{
12186 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
12187}
12188
INADA Naoki3ae20562017-01-16 20:41:20 +090012189/*[clinic input]
12190str.isprintable as unicode_isprintable
Georg Brandl559e5d72008-06-11 18:37:52 +000012191
INADA Naoki3ae20562017-01-16 20:41:20 +090012192Return True if the string is printable, False otherwise.
12193
12194A string is printable if all of its characters are considered printable in
12195repr() or if it is empty.
12196[clinic start generated code]*/
12197
12198static PyObject *
12199unicode_isprintable_impl(PyObject *self)
INADA Naoki15f94592017-01-16 21:49:13 +090012200/*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
Georg Brandl559e5d72008-06-11 18:37:52 +000012201{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012202 Py_ssize_t i, length;
12203 int kind;
12204 void *data;
12205
12206 if (PyUnicode_READY(self) == -1)
12207 return NULL;
12208 length = PyUnicode_GET_LENGTH(self);
12209 kind = PyUnicode_KIND(self);
12210 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000012211
12212 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012213 if (length == 1)
12214 return PyBool_FromLong(
12215 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000012216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217 for (i = 0; i < length; i++) {
12218 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012219 Py_RETURN_FALSE;
12220 }
12221 }
12222 Py_RETURN_TRUE;
12223}
12224
INADA Naoki3ae20562017-01-16 20:41:20 +090012225/*[clinic input]
12226str.join as unicode_join
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227
INADA Naoki3ae20562017-01-16 20:41:20 +090012228 iterable: object
12229 /
12230
12231Concatenate any number of strings.
12232
Martin Panter91a88662017-01-24 00:30:06 +000012233The string whose method is called is inserted in between each given string.
INADA Naoki3ae20562017-01-16 20:41:20 +090012234The result is returned as a new string.
12235
12236Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
12237[clinic start generated code]*/
12238
12239static PyObject *
12240unicode_join(PyObject *self, PyObject *iterable)
Martin Panter91a88662017-01-24 00:30:06 +000012241/*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242{
INADA Naoki3ae20562017-01-16 20:41:20 +090012243 return PyUnicode_Join(self, iterable);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244}
12245
Martin v. Löwis18e16552006-02-15 17:27:45 +000012246static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012247unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012248{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012249 if (PyUnicode_READY(self) == -1)
12250 return -1;
12251 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252}
12253
INADA Naoki3ae20562017-01-16 20:41:20 +090012254/*[clinic input]
12255str.ljust as unicode_ljust
12256
12257 width: Py_ssize_t
12258 fillchar: Py_UCS4 = ' '
12259 /
12260
12261Return a left-justified string of length width.
12262
12263Padding is done using the specified fill character (default is a space).
12264[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265
12266static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012267unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12268/*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012270 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012271 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272
Victor Stinnerc4b49542011-12-11 22:44:26 +010012273 if (PyUnicode_GET_LENGTH(self) >= width)
12274 return unicode_result_unchanged(self);
12275
12276 return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277}
12278
INADA Naoki3ae20562017-01-16 20:41:20 +090012279/*[clinic input]
12280str.lower as unicode_lower
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281
INADA Naoki3ae20562017-01-16 20:41:20 +090012282Return a copy of the string converted to lowercase.
12283[clinic start generated code]*/
12284
12285static PyObject *
12286unicode_lower_impl(PyObject *self)
12287/*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050012289 if (PyUnicode_READY(self) == -1)
12290 return NULL;
12291 if (PyUnicode_IS_ASCII(self))
12292 return ascii_upper_or_lower(self, 1);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010012293 return case_operation(self, do_lower);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294}
12295
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012296#define LEFTSTRIP 0
12297#define RIGHTSTRIP 1
12298#define BOTHSTRIP 2
12299
12300/* Arrays indexed by above */
INADA Naoki3ae20562017-01-16 20:41:20 +090012301static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012302
INADA Naoki3ae20562017-01-16 20:41:20 +090012303#define STRIPNAME(i) (stripfuncnames[i])
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012304
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012305/* externally visible for str.strip(unicode) */
12306PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012307_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012308{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 void *data;
12310 int kind;
12311 Py_ssize_t i, j, len;
12312 BLOOM_MASK sepmask;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012313 Py_ssize_t seplen;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012315 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
12316 return NULL;
12317
12318 kind = PyUnicode_KIND(self);
12319 data = PyUnicode_DATA(self);
12320 len = PyUnicode_GET_LENGTH(self);
Victor Stinnerb3a60142013-04-09 22:19:21 +020012321 seplen = PyUnicode_GET_LENGTH(sepobj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
12323 PyUnicode_DATA(sepobj),
Victor Stinnerb3a60142013-04-09 22:19:21 +020012324 seplen);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012325
Benjamin Peterson14339b62009-01-31 16:36:08 +000012326 i = 0;
12327 if (striptype != RIGHTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012328 while (i < len) {
12329 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12330 if (!BLOOM(sepmask, ch))
12331 break;
12332 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12333 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012334 i++;
12335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012336 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012337
Benjamin Peterson14339b62009-01-31 16:36:08 +000012338 j = len;
12339 if (striptype != LEFTSTRIP) {
Victor Stinnerb3a60142013-04-09 22:19:21 +020012340 j--;
12341 while (j >= i) {
12342 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12343 if (!BLOOM(sepmask, ch))
12344 break;
12345 if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
12346 break;
Benjamin Peterson29060642009-01-31 22:14:21 +000012347 j--;
Victor Stinnerb3a60142013-04-09 22:19:21 +020012348 }
12349
Benjamin Peterson29060642009-01-31 22:14:21 +000012350 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012351 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012352
Victor Stinner7931d9a2011-11-04 00:22:48 +010012353 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012354}
12355
12356PyObject*
12357PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
12358{
12359 unsigned char *data;
12360 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020012361 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012362
Victor Stinnerde636f32011-10-01 03:55:54 +020012363 if (PyUnicode_READY(self) == -1)
12364 return NULL;
12365
Victor Stinner684d5fd2012-05-03 02:32:34 +020012366 length = PyUnicode_GET_LENGTH(self);
12367 end = Py_MIN(end, length);
Victor Stinnerde636f32011-10-01 03:55:54 +020012368
Victor Stinner684d5fd2012-05-03 02:32:34 +020012369 if (start == 0 && end == length)
Victor Stinnerc4b49542011-12-11 22:44:26 +010012370 return unicode_result_unchanged(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012371
Victor Stinnerde636f32011-10-01 03:55:54 +020012372 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020012373 PyErr_SetString(PyExc_IndexError, "string index out of range");
12374 return NULL;
12375 }
Serhiy Storchaka678db842013-01-26 12:16:36 +020012376 if (start >= length || end < start)
12377 _Py_RETURN_UNICODE_EMPTY();
Victor Stinner12bab6d2011-10-01 01:53:49 +020012378
Victor Stinner684d5fd2012-05-03 02:32:34 +020012379 length = end - start;
Victor Stinnerb9275c12011-10-05 14:01:42 +020012380 if (PyUnicode_IS_ASCII(self)) {
Victor Stinnerb9275c12011-10-05 14:01:42 +020012381 data = PyUnicode_1BYTE_DATA(self);
Victor Stinnerd3f08822012-05-29 12:57:52 +020012382 return _PyUnicode_FromASCII((char*)(data + start), length);
Victor Stinnerb9275c12011-10-05 14:01:42 +020012383 }
12384 else {
12385 kind = PyUnicode_KIND(self);
12386 data = PyUnicode_1BYTE_DATA(self);
12387 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012388 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020012389 length);
12390 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012391}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012392
12393static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012394do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012395{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012396 Py_ssize_t len, i, j;
12397
12398 if (PyUnicode_READY(self) == -1)
12399 return NULL;
12400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012402
Victor Stinnercc7af722013-04-09 22:39:24 +020012403 if (PyUnicode_IS_ASCII(self)) {
12404 Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
12405
12406 i = 0;
12407 if (striptype != RIGHTSTRIP) {
12408 while (i < len) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012409 Py_UCS1 ch = data[i];
Victor Stinnercc7af722013-04-09 22:39:24 +020012410 if (!_Py_ascii_whitespace[ch])
12411 break;
12412 i++;
12413 }
12414 }
12415
12416 j = len;
12417 if (striptype != LEFTSTRIP) {
12418 j--;
12419 while (j >= i) {
Victor Stinnerd92e0782013-04-14 19:17:42 +020012420 Py_UCS1 ch = data[j];
Victor Stinnercc7af722013-04-09 22:39:24 +020012421 if (!_Py_ascii_whitespace[ch])
12422 break;
12423 j--;
12424 }
12425 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012426 }
12427 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012428 else {
12429 int kind = PyUnicode_KIND(self);
12430 void *data = PyUnicode_DATA(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012431
Victor Stinnercc7af722013-04-09 22:39:24 +020012432 i = 0;
12433 if (striptype != RIGHTSTRIP) {
12434 while (i < len) {
12435 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
12436 if (!Py_UNICODE_ISSPACE(ch))
12437 break;
12438 i++;
12439 }
Victor Stinner9c79e412013-04-09 22:21:08 +020012440 }
Victor Stinnercc7af722013-04-09 22:39:24 +020012441
12442 j = len;
12443 if (striptype != LEFTSTRIP) {
12444 j--;
12445 while (j >= i) {
12446 Py_UCS4 ch = PyUnicode_READ(kind, data, j);
12447 if (!Py_UNICODE_ISSPACE(ch))
12448 break;
12449 j--;
12450 }
12451 j++;
12452 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000012453 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012454
Victor Stinner7931d9a2011-11-04 00:22:48 +010012455 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012456}
12457
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012458
12459static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012460do_argstrip(PyObject *self, int striptype, PyObject *sep)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012461{
Benjamin Peterson14339b62009-01-31 16:36:08 +000012462 if (sep != NULL && sep != Py_None) {
12463 if (PyUnicode_Check(sep))
12464 return _PyUnicode_XStrip(self, striptype, sep);
12465 else {
12466 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000012467 "%s arg must be None or str",
12468 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000012469 return NULL;
12470 }
12471 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012472
Benjamin Peterson14339b62009-01-31 16:36:08 +000012473 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012474}
12475
12476
INADA Naoki3ae20562017-01-16 20:41:20 +090012477/*[clinic input]
12478str.strip as unicode_strip
12479
12480 chars: object = None
12481 /
12482
Victor Stinner0c4a8282017-01-17 02:21:47 +010012483Return a copy of the string with leading and trailing whitespace remove.
INADA Naoki3ae20562017-01-16 20:41:20 +090012484
12485If chars is given and not None, remove characters in chars instead.
12486[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012487
12488static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012489unicode_strip_impl(PyObject *self, PyObject *chars)
Victor Stinner0c4a8282017-01-17 02:21:47 +010012490/*[clinic end generated code: output=ca19018454345d57 input=eefe24a1059c352b]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012491{
INADA Naoki3ae20562017-01-16 20:41:20 +090012492 return do_argstrip(self, BOTHSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012493}
12494
12495
INADA Naoki3ae20562017-01-16 20:41:20 +090012496/*[clinic input]
12497str.lstrip as unicode_lstrip
12498
12499 chars: object = NULL
12500 /
12501
12502Return a copy of the string with leading whitespace removed.
12503
12504If chars is given and not None, remove characters in chars instead.
12505[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012506
12507static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012508unicode_lstrip_impl(PyObject *self, PyObject *chars)
12509/*[clinic end generated code: output=3b43683251f79ca7 input=9e56f3c45f5ff4c3]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012510{
INADA Naoki3ae20562017-01-16 20:41:20 +090012511 return do_argstrip(self, LEFTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012512}
12513
12514
INADA Naoki3ae20562017-01-16 20:41:20 +090012515/*[clinic input]
12516str.rstrip as unicode_rstrip
12517
12518 chars: object = NULL
12519 /
12520
12521Return a copy of the string with trailing whitespace removed.
12522
12523If chars is given and not None, remove characters in chars instead.
12524[clinic start generated code]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012525
12526static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012527unicode_rstrip_impl(PyObject *self, PyObject *chars)
12528/*[clinic end generated code: output=4a59230017cc3b7a input=ac89d0219cb411ee]*/
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012529{
INADA Naoki3ae20562017-01-16 20:41:20 +090012530 return do_argstrip(self, RIGHTSTRIP, chars);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012531}
12532
12533
Guido van Rossumd57fd912000-03-10 22:53:23 +000012534static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012535unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012537 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012539
Serhiy Storchaka05997252013-01-26 12:14:02 +020012540 if (len < 1)
12541 _Py_RETURN_UNICODE_EMPTY();
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542
Victor Stinnerc4b49542011-12-11 22:44:26 +010012543 /* no repeat, return original string */
12544 if (len == 1)
12545 return unicode_result_unchanged(str);
Tim Peters8f422462000-09-09 06:13:41 +000012546
Benjamin Petersonbac79492012-01-14 13:34:47 -050012547 if (PyUnicode_READY(str) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012548 return NULL;
12549
Victor Stinnerc759f3e2011-10-01 03:09:58 +020012550 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020012551 PyErr_SetString(PyExc_OverflowError,
12552 "repeated string is too long");
12553 return NULL;
12554 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012555 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012556
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012557 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012558 if (!u)
12559 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012560 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012561
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012562 if (PyUnicode_GET_LENGTH(str) == 1) {
12563 const int kind = PyUnicode_KIND(str);
12564 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
Victor Stinner73f53b52011-12-18 03:26:31 +010012565 if (kind == PyUnicode_1BYTE_KIND) {
12566 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012567 memset(to, (unsigned char)fill_char, len);
Victor Stinner73f53b52011-12-18 03:26:31 +010012568 }
12569 else if (kind == PyUnicode_2BYTE_KIND) {
12570 Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012571 for (n = 0; n < len; ++n)
Victor Stinner73f53b52011-12-18 03:26:31 +010012572 ucs2[n] = fill_char;
12573 } else {
12574 Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
12575 assert(kind == PyUnicode_4BYTE_KIND);
12576 for (n = 0; n < len; ++n)
12577 ucs4[n] = fill_char;
Victor Stinner67ca64c2011-10-01 02:47:29 +020012578 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012579 }
12580 else {
12581 /* number of characters copied this far */
12582 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012583 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 char *to = (char *) PyUnicode_DATA(u);
Christian Heimesf051e432016-09-13 20:22:02 +020012585 memcpy(to, PyUnicode_DATA(str),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012586 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012587 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588 n = (done <= nchars-done) ? done : nchars-done;
Christian Heimesf051e432016-09-13 20:22:02 +020012589 memcpy(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012590 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012591 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012592 }
12593
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012594 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012595 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012596}
12597
Alexander Belopolsky40018472011-02-26 01:02:56 +000012598PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012599PyUnicode_Replace(PyObject *str,
12600 PyObject *substr,
12601 PyObject *replstr,
Alexander Belopolsky40018472011-02-26 01:02:56 +000012602 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012603{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012604 if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
12605 ensure_unicode(replstr) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012606 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012607 return replace(str, substr, replstr, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608}
12609
INADA Naoki3ae20562017-01-16 20:41:20 +090012610/*[clinic input]
12611str.replace as unicode_replace
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612
INADA Naoki3ae20562017-01-16 20:41:20 +090012613 old: unicode
12614 new: unicode
12615 count: Py_ssize_t = -1
12616 Maximum number of occurrences to replace.
12617 -1 (the default value) means replace all occurrences.
12618 /
12619
12620Return a copy with all occurrences of substring old replaced by new.
12621
12622If the optional argument count is given, only the first count occurrences are
12623replaced.
12624[clinic start generated code]*/
12625
12626static PyObject *
12627unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
12628 Py_ssize_t count)
12629/*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630{
Benjamin Peterson22a29702012-01-02 09:00:30 -060012631 if (PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012632 return NULL;
INADA Naoki3ae20562017-01-16 20:41:20 +090012633 return replace(self, old, new, count);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012634}
12635
Alexander Belopolsky40018472011-02-26 01:02:56 +000012636static PyObject *
12637unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012639 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012640 Py_ssize_t isize;
12641 Py_ssize_t osize, squote, dquote, i, o;
12642 Py_UCS4 max, quote;
Victor Stinner55c08782013-04-14 18:45:39 +020012643 int ikind, okind, unchanged;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012644 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012646 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012647 return NULL;
12648
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012649 isize = PyUnicode_GET_LENGTH(unicode);
12650 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012652 /* Compute length of output, quote characters, and
12653 maximum character */
Victor Stinner55c08782013-04-14 18:45:39 +020012654 osize = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 max = 127;
12656 squote = dquote = 0;
12657 ikind = PyUnicode_KIND(unicode);
12658 for (i = 0; i < isize; i++) {
12659 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Benjamin Peterson736b8012014-09-29 23:02:15 -040012660 Py_ssize_t incr = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 switch (ch) {
Benjamin Peterson736b8012014-09-29 23:02:15 -040012662 case '\'': squote++; break;
12663 case '"': dquote++; break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012664 case '\\': case '\t': case '\r': case '\n':
Benjamin Peterson736b8012014-09-29 23:02:15 -040012665 incr = 2;
12666 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012667 default:
12668 /* Fast-path ASCII */
12669 if (ch < ' ' || ch == 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012670 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012671 else if (ch < 0x7f)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012672 ;
12673 else if (Py_UNICODE_ISPRINTABLE(ch))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 max = ch > max ? ch : max;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 else if (ch < 0x100)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012676 incr = 4; /* \xHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012677 else if (ch < 0x10000)
Benjamin Peterson736b8012014-09-29 23:02:15 -040012678 incr = 6; /* \uHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012679 else
Benjamin Peterson736b8012014-09-29 23:02:15 -040012680 incr = 10; /* \uHHHHHHHH */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 }
Benjamin Peterson736b8012014-09-29 23:02:15 -040012682 if (osize > PY_SSIZE_T_MAX - incr) {
12683 PyErr_SetString(PyExc_OverflowError,
12684 "string is too long to generate repr");
12685 return NULL;
12686 }
12687 osize += incr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012688 }
12689
12690 quote = '\'';
Victor Stinner55c08782013-04-14 18:45:39 +020012691 unchanged = (osize == isize);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012692 if (squote) {
Victor Stinner55c08782013-04-14 18:45:39 +020012693 unchanged = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012694 if (dquote)
12695 /* Both squote and dquote present. Use squote,
12696 and escape them */
12697 osize += squote;
12698 else
12699 quote = '"';
12700 }
Victor Stinner55c08782013-04-14 18:45:39 +020012701 osize += 2; /* quotes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012702
12703 repr = PyUnicode_New(osize, max);
12704 if (repr == NULL)
12705 return NULL;
12706 okind = PyUnicode_KIND(repr);
12707 odata = PyUnicode_DATA(repr);
12708
12709 PyUnicode_WRITE(okind, odata, 0, quote);
12710 PyUnicode_WRITE(okind, odata, osize-1, quote);
Victor Stinner55c08782013-04-14 18:45:39 +020012711 if (unchanged) {
12712 _PyUnicode_FastCopyCharacters(repr, 1,
12713 unicode, 0,
12714 isize);
12715 }
12716 else {
12717 for (i = 0, o = 1; i < isize; i++) {
12718 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012719
Victor Stinner55c08782013-04-14 18:45:39 +020012720 /* Escape quotes and backslashes */
12721 if ((ch == quote) || (ch == '\\')) {
Kristján Valur Jónsson55e5dc82012-06-06 21:58:08 +000012722 PyUnicode_WRITE(okind, odata, o++, '\\');
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 PyUnicode_WRITE(okind, odata, o++, ch);
Victor Stinner55c08782013-04-14 18:45:39 +020012724 continue;
12725 }
12726
12727 /* Map special whitespace to '\t', \n', '\r' */
12728 if (ch == '\t') {
12729 PyUnicode_WRITE(okind, odata, o++, '\\');
12730 PyUnicode_WRITE(okind, odata, o++, 't');
12731 }
12732 else if (ch == '\n') {
12733 PyUnicode_WRITE(okind, odata, o++, '\\');
12734 PyUnicode_WRITE(okind, odata, o++, 'n');
12735 }
12736 else if (ch == '\r') {
12737 PyUnicode_WRITE(okind, odata, o++, '\\');
12738 PyUnicode_WRITE(okind, odata, o++, 'r');
12739 }
12740
12741 /* Map non-printable US ASCII to '\xhh' */
12742 else if (ch < ' ' || ch == 0x7F) {
12743 PyUnicode_WRITE(okind, odata, o++, '\\');
12744 PyUnicode_WRITE(okind, odata, o++, 'x');
12745 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12746 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12747 }
12748
12749 /* Copy ASCII characters as-is */
12750 else if (ch < 0x7F) {
12751 PyUnicode_WRITE(okind, odata, o++, ch);
12752 }
12753
12754 /* Non-ASCII characters */
12755 else {
12756 /* Map Unicode whitespace and control characters
12757 (categories Z* and C* except ASCII space)
12758 */
12759 if (!Py_UNICODE_ISPRINTABLE(ch)) {
12760 PyUnicode_WRITE(okind, odata, o++, '\\');
12761 /* Map 8-bit characters to '\xhh' */
12762 if (ch <= 0xff) {
12763 PyUnicode_WRITE(okind, odata, o++, 'x');
12764 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12765 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
12766 }
12767 /* Map 16-bit characters to '\uxxxx' */
12768 else if (ch <= 0xffff) {
12769 PyUnicode_WRITE(okind, odata, o++, 'u');
12770 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12771 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12772 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12773 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12774 }
12775 /* Map 21-bit characters to '\U00xxxxxx' */
12776 else {
12777 PyUnicode_WRITE(okind, odata, o++, 'U');
12778 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12779 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12780 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12781 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12782 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12783 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12784 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12785 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
12786 }
12787 }
12788 /* Copy characters as-is */
12789 else {
12790 PyUnicode_WRITE(okind, odata, o++, ch);
12791 }
Georg Brandl559e5d72008-06-11 18:37:52 +000012792 }
12793 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012794 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012795 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012796 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012797 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798}
12799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012800PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012801 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802\n\
12803Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012804such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805arguments start and end are interpreted as in slice notation.\n\
12806\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012807Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808
12809static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012811{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012812 /* initialize variables to prevent gcc warning */
12813 PyObject *substring = NULL;
12814 Py_ssize_t start = 0;
12815 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012816 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012817
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012818 if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012819 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012821 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012822 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012823
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012824 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012825
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012826 if (result == -2)
12827 return NULL;
12828
Christian Heimes217cfd12007-12-02 14:31:20 +000012829 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830}
12831
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012832PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012833 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834\n\
Lisa Roach43ba8862017-04-04 22:36:22 -070012835Return the highest index in S where substring sub is found,\n\
12836such that sub is contained within S[start:end]. Optional\n\
12837arguments start and end are interpreted as in slice notation.\n\
12838\n\
12839Raises ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012840
12841static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012842unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843{
Victor Stinner0c39b1b2015-03-18 15:02:06 +010012844 /* initialize variables to prevent gcc warning */
12845 PyObject *substring = NULL;
12846 Py_ssize_t start = 0;
12847 Py_ssize_t end = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012848 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849
Serhiy Storchakadd40fc32016-05-04 22:23:26 +030012850 if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012851 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012852
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012853 if (PyUnicode_READY(self) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012855
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012856 result = any_find_slice(self, substring, start, end, -1);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858 if (result == -2)
12859 return NULL;
12860
Guido van Rossumd57fd912000-03-10 22:53:23 +000012861 if (result < 0) {
12862 PyErr_SetString(PyExc_ValueError, "substring not found");
12863 return NULL;
12864 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012865
Christian Heimes217cfd12007-12-02 14:31:20 +000012866 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012867}
12868
INADA Naoki3ae20562017-01-16 20:41:20 +090012869/*[clinic input]
12870str.rjust as unicode_rjust
12871
12872 width: Py_ssize_t
12873 fillchar: Py_UCS4 = ' '
12874 /
12875
12876Return a right-justified string of length width.
12877
12878Padding is done using the specified fill character (default is a space).
12879[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012880
12881static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090012882unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
12883/*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884{
Benjamin Petersonbac79492012-01-14 13:34:47 -050012885 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886 return NULL;
12887
Victor Stinnerc4b49542011-12-11 22:44:26 +010012888 if (PyUnicode_GET_LENGTH(self) >= width)
12889 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012890
Victor Stinnerc4b49542011-12-11 22:44:26 +010012891 return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892}
12893
Alexander Belopolsky40018472011-02-26 01:02:56 +000012894PyObject *
12895PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012896{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012897 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012898 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012899
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012900 return split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901}
12902
INADA Naoki3ae20562017-01-16 20:41:20 +090012903/*[clinic input]
12904str.split as unicode_split
Guido van Rossumd57fd912000-03-10 22:53:23 +000012905
INADA Naoki3ae20562017-01-16 20:41:20 +090012906 sep: object = None
12907 The delimiter according which to split the string.
12908 None (the default value) means split according to any whitespace,
12909 and discard empty strings from the result.
12910 maxsplit: Py_ssize_t = -1
12911 Maximum number of splits to do.
12912 -1 (the default value) means no limit.
12913
12914Return a list of the words in the string, using sep as the delimiter string.
12915[clinic start generated code]*/
12916
12917static PyObject *
12918unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
12919/*[clinic end generated code: output=3a65b1db356948dc input=606e750488a82359]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920{
INADA Naoki3ae20562017-01-16 20:41:20 +090012921 if (sep == Py_None)
12922 return split(self, NULL, maxsplit);
12923 if (PyUnicode_Check(sep))
12924 return split(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012925
Victor Stinner998b8062018-09-12 00:23:25 +020012926 PyErr_Format(PyExc_TypeError,
12927 "must be str or None, not %.100s",
12928 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012929 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012930}
12931
Thomas Wouters477c8d52006-05-27 19:21:47 +000012932PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012933PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012934{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012935 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012936 int kind1, kind2;
12937 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012938 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012939
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012940 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012941 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012942
Victor Stinner14f8f022011-10-05 20:58:25 +020012943 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012944 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012945 len1 = PyUnicode_GET_LENGTH(str_obj);
12946 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012947 if (kind1 < kind2 || len1 < len2) {
12948 _Py_INCREF_UNICODE_EMPTY();
12949 if (!unicode_empty)
12950 out = NULL;
12951 else {
12952 out = PyTuple_Pack(3, str_obj, unicode_empty, unicode_empty);
12953 Py_DECREF(unicode_empty);
12954 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012955 return out;
12956 }
12957 buf1 = PyUnicode_DATA(str_obj);
12958 buf2 = PyUnicode_DATA(sep_obj);
12959 if (kind2 != kind1) {
12960 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
12961 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012962 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012963 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012964
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012965 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012966 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012967 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12968 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12969 else
12970 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012971 break;
12972 case PyUnicode_2BYTE_KIND:
12973 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12974 break;
12975 case PyUnicode_4BYTE_KIND:
12976 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12977 break;
12978 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070012979 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012981
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012982 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012983 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012984
12985 return out;
12986}
12987
12988
12989PyObject *
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012990PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012991{
Thomas Wouters477c8d52006-05-27 19:21:47 +000012992 PyObject* out;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020012993 int kind1, kind2;
12994 void *buf1, *buf2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012995 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012996
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030012997 if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000012998 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012999
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013000 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013001 kind2 = PyUnicode_KIND(sep_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 len1 = PyUnicode_GET_LENGTH(str_obj);
13003 len2 = PyUnicode_GET_LENGTH(sep_obj);
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013004 if (kind1 < kind2 || len1 < len2) {
13005 _Py_INCREF_UNICODE_EMPTY();
13006 if (!unicode_empty)
13007 out = NULL;
13008 else {
13009 out = PyTuple_Pack(3, unicode_empty, unicode_empty, str_obj);
13010 Py_DECREF(unicode_empty);
13011 }
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013012 return out;
13013 }
13014 buf1 = PyUnicode_DATA(str_obj);
13015 buf2 = PyUnicode_DATA(sep_obj);
13016 if (kind2 != kind1) {
13017 buf2 = _PyUnicode_AsKind(sep_obj, kind1);
13018 if (!buf2)
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013019 return NULL;
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013020 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013021
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013022 switch (kind1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013023 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020013024 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
13025 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13026 else
13027 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013028 break;
13029 case PyUnicode_2BYTE_KIND:
13030 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13031 break;
13032 case PyUnicode_4BYTE_KIND:
13033 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
13034 break;
13035 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013036 Py_UNREACHABLE();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013037 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000013038
Serhiy Storchakad9d769f2015-03-24 21:55:47 +020013039 if (kind2 != kind1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013040 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013041
13042 return out;
13043}
13044
INADA Naoki3ae20562017-01-16 20:41:20 +090013045/*[clinic input]
13046str.partition as unicode_partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013047
INADA Naoki3ae20562017-01-16 20:41:20 +090013048 sep: object
13049 /
13050
13051Partition the string into three parts using the given separator.
13052
13053This will search for the separator in the string. If the separator is found,
13054returns a 3-tuple containing the part before the separator, the separator
13055itself, and the part after it.
13056
13057If the separator is not found, returns a 3-tuple containing the original string
13058and two empty strings.
13059[clinic start generated code]*/
13060
13061static PyObject *
13062unicode_partition(PyObject *self, PyObject *sep)
13063/*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013064{
INADA Naoki3ae20562017-01-16 20:41:20 +090013065 return PyUnicode_Partition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013066}
13067
INADA Naoki3ae20562017-01-16 20:41:20 +090013068/*[clinic input]
13069str.rpartition as unicode_rpartition = str.partition
Thomas Wouters477c8d52006-05-27 19:21:47 +000013070
INADA Naoki3ae20562017-01-16 20:41:20 +090013071Partition the string into three parts using the given separator.
13072
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013073This will search for the separator in the string, starting at the end. If
INADA Naoki3ae20562017-01-16 20:41:20 +090013074the separator is found, returns a 3-tuple containing the part before the
13075separator, the separator itself, and the part after it.
13076
13077If the separator is not found, returns a 3-tuple containing two empty strings
13078and the original string.
13079[clinic start generated code]*/
13080
13081static PyObject *
13082unicode_rpartition(PyObject *self, PyObject *sep)
Serhiy Storchakaa2314282017-10-29 02:11:54 +030013083/*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
Thomas Wouters477c8d52006-05-27 19:21:47 +000013084{
INADA Naoki3ae20562017-01-16 20:41:20 +090013085 return PyUnicode_RPartition(self, sep);
Thomas Wouters477c8d52006-05-27 19:21:47 +000013086}
13087
Alexander Belopolsky40018472011-02-26 01:02:56 +000013088PyObject *
13089PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013090{
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013091 if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013092 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013093
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013094 return rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013095}
13096
INADA Naoki3ae20562017-01-16 20:41:20 +090013097/*[clinic input]
13098str.rsplit as unicode_rsplit = str.split
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013099
INADA Naoki3ae20562017-01-16 20:41:20 +090013100Return a list of the words in the string, using sep as the delimiter string.
13101
13102Splits are done starting at the end of the string and working to the front.
13103[clinic start generated code]*/
13104
13105static PyObject *
13106unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
13107/*[clinic end generated code: output=c2b815c63bcabffc input=12ad4bf57dd35f15]*/
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013108{
INADA Naoki3ae20562017-01-16 20:41:20 +090013109 if (sep == Py_None)
13110 return rsplit(self, NULL, maxsplit);
13111 if (PyUnicode_Check(sep))
13112 return rsplit(self, sep, maxsplit);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013113
Victor Stinner998b8062018-09-12 00:23:25 +020013114 PyErr_Format(PyExc_TypeError,
13115 "must be str or None, not %.100s",
13116 Py_TYPE(sep)->tp_name);
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013117 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013118}
13119
INADA Naoki3ae20562017-01-16 20:41:20 +090013120/*[clinic input]
13121str.splitlines as unicode_splitlines
Guido van Rossumd57fd912000-03-10 22:53:23 +000013122
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013123 keepends: bool(accept={int}) = False
INADA Naoki3ae20562017-01-16 20:41:20 +090013124
13125Return a list of the lines in the string, breaking at line boundaries.
13126
13127Line breaks are not included in the resulting list unless keepends is given and
13128true.
13129[clinic start generated code]*/
13130
13131static PyObject *
13132unicode_splitlines_impl(PyObject *self, int keepends)
Serhiy Storchaka202fda52017-03-12 10:10:47 +020013133/*[clinic end generated code: output=f664dcdad153ec40 input=b508e180459bdd8b]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013134{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013135 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013136}
13137
13138static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000013139PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013140{
Victor Stinnerc4b49542011-12-11 22:44:26 +010013141 return unicode_result_unchanged(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013142}
13143
INADA Naoki3ae20562017-01-16 20:41:20 +090013144/*[clinic input]
13145str.swapcase as unicode_swapcase
Guido van Rossumd57fd912000-03-10 22:53:23 +000013146
INADA Naoki3ae20562017-01-16 20:41:20 +090013147Convert uppercase characters to lowercase and lowercase characters to uppercase.
13148[clinic start generated code]*/
13149
13150static PyObject *
13151unicode_swapcase_impl(PyObject *self)
13152/*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013153{
Benjamin Petersoneea48462012-01-16 14:28:50 -050013154 if (PyUnicode_READY(self) == -1)
13155 return NULL;
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013156 return case_operation(self, do_swapcase);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013157}
13158
Larry Hastings61272b72014-01-07 12:41:53 -080013159/*[clinic input]
Georg Brandlceee0772007-11-27 23:48:05 +000013160
Larry Hastings31826802013-10-19 00:09:25 -070013161@staticmethod
13162str.maketrans as unicode_maketrans
13163
13164 x: object
13165
13166 y: unicode=NULL
13167
13168 z: unicode=NULL
13169
13170 /
13171
13172Return a translation table usable for str.translate().
13173
13174If there is only one argument, it must be a dictionary mapping Unicode
13175ordinals (integers) or characters to Unicode ordinals, strings or None.
13176Character keys will be then converted to ordinals.
13177If there are two arguments, they must be strings of equal length, and
13178in the resulting dictionary, each character in x will be mapped to the
13179character at the same position in y. If there is a third argument, it
13180must be a string, whose characters will be mapped to None in the result.
Larry Hastings61272b72014-01-07 12:41:53 -080013181[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -070013182
Larry Hastings31826802013-10-19 00:09:25 -070013183static PyObject *
Larry Hastings5c661892014-01-24 06:17:25 -080013184unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
Serhiy Storchaka1009bf12015-04-03 23:53:51 +030013185/*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
Larry Hastings31826802013-10-19 00:09:25 -070013186{
Georg Brandlceee0772007-11-27 23:48:05 +000013187 PyObject *new = NULL, *key, *value;
13188 Py_ssize_t i = 0;
13189 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013190
Georg Brandlceee0772007-11-27 23:48:05 +000013191 new = PyDict_New();
13192 if (!new)
13193 return NULL;
13194 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013195 int x_kind, y_kind, z_kind;
13196 void *x_data, *y_data, *z_data;
13197
Georg Brandlceee0772007-11-27 23:48:05 +000013198 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000013199 if (!PyUnicode_Check(x)) {
13200 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
13201 "be a string if there is a second argument");
13202 goto err;
13203 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013204 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013205 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
13206 "arguments must have equal length");
13207 goto err;
13208 }
13209 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013210 x_kind = PyUnicode_KIND(x);
13211 y_kind = PyUnicode_KIND(y);
13212 x_data = PyUnicode_DATA(x);
13213 y_data = PyUnicode_DATA(y);
13214 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
13215 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013216 if (!key)
Georg Brandlceee0772007-11-27 23:48:05 +000013217 goto err;
Benjamin Peterson822c7902011-12-20 13:32:50 -060013218 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Benjamin Peterson53aa1d72011-12-20 13:29:45 -060013219 if (!value) {
13220 Py_DECREF(key);
13221 goto err;
13222 }
Georg Brandlceee0772007-11-27 23:48:05 +000013223 res = PyDict_SetItem(new, key, value);
13224 Py_DECREF(key);
13225 Py_DECREF(value);
13226 if (res < 0)
13227 goto err;
13228 }
13229 /* create entries for deleting chars in z */
13230 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013231 z_kind = PyUnicode_KIND(z);
13232 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013233 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013234 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000013235 if (!key)
13236 goto err;
13237 res = PyDict_SetItem(new, key, Py_None);
13238 Py_DECREF(key);
13239 if (res < 0)
13240 goto err;
13241 }
13242 }
13243 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013244 int kind;
13245 void *data;
13246
Georg Brandlceee0772007-11-27 23:48:05 +000013247 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000013248 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013249 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
13250 "to maketrans it must be a dict");
13251 goto err;
13252 }
13253 /* copy entries into the new dict, converting string keys to int keys */
13254 while (PyDict_Next(x, &i, &key, &value)) {
13255 if (PyUnicode_Check(key)) {
13256 /* convert string keys to integer keys */
13257 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020013258 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000013259 PyErr_SetString(PyExc_ValueError, "string keys in translate "
13260 "table must be of length 1");
13261 goto err;
13262 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013263 kind = PyUnicode_KIND(key);
13264 data = PyUnicode_DATA(key);
13265 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000013266 if (!newkey)
13267 goto err;
13268 res = PyDict_SetItem(new, newkey, value);
13269 Py_DECREF(newkey);
13270 if (res < 0)
13271 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000013272 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000013273 /* just keep integer keys */
13274 if (PyDict_SetItem(new, key, value) < 0)
13275 goto err;
13276 } else {
13277 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
13278 "be strings or integers");
13279 goto err;
13280 }
13281 }
13282 }
13283 return new;
13284 err:
13285 Py_DECREF(new);
13286 return NULL;
13287}
13288
INADA Naoki3ae20562017-01-16 20:41:20 +090013289/*[clinic input]
13290str.translate as unicode_translate
Guido van Rossumd57fd912000-03-10 22:53:23 +000013291
INADA Naoki3ae20562017-01-16 20:41:20 +090013292 table: object
13293 Translation table, which must be a mapping of Unicode ordinals to
13294 Unicode ordinals, strings, or None.
13295 /
13296
13297Replace each character in the string using the given translation table.
13298
13299The table must implement lookup/indexing via __getitem__, for instance a
13300dictionary or list. If this operation raises LookupError, the character is
13301left untouched. Characters mapped to None are deleted.
13302[clinic start generated code]*/
13303
13304static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013305unicode_translate(PyObject *self, PyObject *table)
INADA Naoki3ae20562017-01-16 20:41:20 +090013306/*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013307{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013308 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013309}
13310
INADA Naoki3ae20562017-01-16 20:41:20 +090013311/*[clinic input]
13312str.upper as unicode_upper
Guido van Rossumd57fd912000-03-10 22:53:23 +000013313
INADA Naoki3ae20562017-01-16 20:41:20 +090013314Return a copy of the string converted to uppercase.
13315[clinic start generated code]*/
13316
13317static PyObject *
13318unicode_upper_impl(PyObject *self)
13319/*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320{
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -050013321 if (PyUnicode_READY(self) == -1)
13322 return NULL;
13323 if (PyUnicode_IS_ASCII(self))
13324 return ascii_upper_or_lower(self, 0);
Victor Stinnerb0800dc2012-02-25 00:47:08 +010013325 return case_operation(self, do_upper);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326}
13327
INADA Naoki3ae20562017-01-16 20:41:20 +090013328/*[clinic input]
13329str.zfill as unicode_zfill
13330
13331 width: Py_ssize_t
13332 /
13333
13334Pad a numeric string with zeros on the left, to fill a field of the given width.
13335
13336The string is never truncated.
13337[clinic start generated code]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013338
13339static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013340unicode_zfill_impl(PyObject *self, Py_ssize_t width)
INADA Naoki15f94592017-01-16 21:49:13 +090013341/*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000013342{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013343 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020013344 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013345 int kind;
13346 void *data;
13347 Py_UCS4 chr;
13348
Benjamin Petersonbac79492012-01-14 13:34:47 -050013349 if (PyUnicode_READY(self) == -1)
Victor Stinnerc4b49542011-12-11 22:44:26 +010013350 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013351
Victor Stinnerc4b49542011-12-11 22:44:26 +010013352 if (PyUnicode_GET_LENGTH(self) >= width)
13353 return unicode_result_unchanged(self);
13354
13355 fill = width - PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013356
13357 u = pad(self, fill, 0, '0');
13358
Walter Dörwald068325e2002-04-15 13:36:47 +000013359 if (u == NULL)
13360 return NULL;
13361
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013362 kind = PyUnicode_KIND(u);
13363 data = PyUnicode_DATA(u);
13364 chr = PyUnicode_READ(kind, data, fill);
13365
13366 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000013367 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013368 PyUnicode_WRITE(kind, data, 0, chr);
13369 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000013370 }
13371
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013372 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010013373 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013374}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013375
13376#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013377static PyObject *
13378unicode__decimal2ascii(PyObject *self)
13379{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013380 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013381}
Guido van Rossumd57fd912000-03-10 22:53:23 +000013382#endif
13383
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013384PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013385 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013386\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013387Return True if S starts with the specified prefix, False otherwise.\n\
13388With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013389With optional end, stop comparing S at that position.\n\
13390prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013391
13392static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013393unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013395{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013396 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013397 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013398 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013399 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013400 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013401
Jesus Ceaac451502011-04-20 17:09:23 +020013402 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013403 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013404 if (PyTuple_Check(subobj)) {
13405 Py_ssize_t i;
13406 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013407 substring = PyTuple_GET_ITEM(subobj, i);
13408 if (!PyUnicode_Check(substring)) {
13409 PyErr_Format(PyExc_TypeError,
13410 "tuple for startswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013411 "not %.100s",
13412 Py_TYPE(substring)->tp_name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013413 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013414 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013415 result = tailmatch(self, substring, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013416 if (result == -1)
13417 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013418 if (result) {
13419 Py_RETURN_TRUE;
13420 }
13421 }
13422 /* nothing matched */
13423 Py_RETURN_FALSE;
13424 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013425 if (!PyUnicode_Check(subobj)) {
13426 PyErr_Format(PyExc_TypeError,
13427 "startswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013428 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013429 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013430 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013431 result = tailmatch(self, subobj, start, end, -1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013432 if (result == -1)
13433 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013434 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013435}
13436
13437
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013438PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013439 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000013440\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000013441Return True if S ends with the specified suffix, False otherwise.\n\
13442With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013443With optional end, stop comparing S at that position.\n\
13444suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013445
13446static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013447unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000013448 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013449{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013450 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013451 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000013452 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013453 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013454 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013455
Jesus Ceaac451502011-04-20 17:09:23 +020013456 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013458 if (PyTuple_Check(subobj)) {
13459 Py_ssize_t i;
13460 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013461 substring = PyTuple_GET_ITEM(subobj, i);
13462 if (!PyUnicode_Check(substring)) {
13463 PyErr_Format(PyExc_TypeError,
13464 "tuple for endswith must only contain str, "
Victor Stinner998b8062018-09-12 00:23:25 +020013465 "not %.100s",
13466 Py_TYPE(substring)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013467 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013468 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013469 result = tailmatch(self, substring, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013470 if (result == -1)
13471 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013472 if (result) {
13473 Py_RETURN_TRUE;
13474 }
13475 }
13476 Py_RETURN_FALSE;
13477 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013478 if (!PyUnicode_Check(subobj)) {
13479 PyErr_Format(PyExc_TypeError,
13480 "endswith first arg must be str or "
Victor Stinner998b8062018-09-12 00:23:25 +020013481 "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000013482 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030013483 }
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030013484 result = tailmatch(self, subobj, start, end, +1);
Victor Stinner18aa4472013-01-03 03:18:09 +010013485 if (result == -1)
13486 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013487 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013488}
13489
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013490static inline void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013491_PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013492{
Victor Stinnereb36fda2015-10-03 01:55:51 +020013493 writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
13494 writer->data = PyUnicode_DATA(writer->buffer);
13495
13496 if (!writer->readonly) {
13497 writer->kind = PyUnicode_KIND(writer->buffer);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013498 writer->size = PyUnicode_GET_LENGTH(writer->buffer);
Victor Stinnereb36fda2015-10-03 01:55:51 +020013499 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013500 else {
Victor Stinnereb36fda2015-10-03 01:55:51 +020013501 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13502 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13503 writer->kind = PyUnicode_WCHAR_KIND;
13504 assert(writer->kind <= PyUnicode_1BYTE_KIND);
13505
Victor Stinner8f674cc2013-04-17 23:02:17 +020013506 /* Copy-on-write mode: set buffer size to 0 so
13507 * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
13508 * next write. */
13509 writer->size = 0;
13510 }
Victor Stinner202fdca2012-05-07 12:47:02 +020013511}
13512
Victor Stinnerd3f08822012-05-29 12:57:52 +020013513void
Victor Stinner8f674cc2013-04-17 23:02:17 +020013514_PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013515{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013516 memset(writer, 0, sizeof(*writer));
Victor Stinnereb36fda2015-10-03 01:55:51 +020013517
13518 /* ASCII is the bare minimum */
Victor Stinner8f674cc2013-04-17 23:02:17 +020013519 writer->min_char = 127;
Victor Stinnereb36fda2015-10-03 01:55:51 +020013520
13521 /* use a value smaller than PyUnicode_1BYTE_KIND() so
13522 _PyUnicodeWriter_PrepareKind() will copy the buffer. */
13523 writer->kind = PyUnicode_WCHAR_KIND;
13524 assert(writer->kind <= PyUnicode_1BYTE_KIND);
Victor Stinner202fdca2012-05-07 12:47:02 +020013525}
13526
Victor Stinnerd3f08822012-05-29 12:57:52 +020013527int
13528_PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
13529 Py_ssize_t length, Py_UCS4 maxchar)
Victor Stinner202fdca2012-05-07 12:47:02 +020013530{
13531 Py_ssize_t newlen;
13532 PyObject *newbuffer;
13533
Victor Stinner2740e462016-09-06 16:58:36 -070013534 assert(maxchar <= MAX_UNICODE);
13535
Victor Stinnerca9381e2015-09-22 00:58:32 +020013536 /* ensure that the _PyUnicodeWriter_Prepare macro was used */
Victor Stinner61744742015-09-22 01:01:17 +020013537 assert((maxchar > writer->maxchar && length >= 0)
13538 || length > 0);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013539
Victor Stinner202fdca2012-05-07 12:47:02 +020013540 if (length > PY_SSIZE_T_MAX - writer->pos) {
13541 PyErr_NoMemory();
13542 return -1;
13543 }
13544 newlen = writer->pos + length;
13545
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070013546 maxchar = Py_MAX(maxchar, writer->min_char);
Victor Stinner8f674cc2013-04-17 23:02:17 +020013547
Victor Stinnerd3f08822012-05-29 12:57:52 +020013548 if (writer->buffer == NULL) {
Victor Stinner8f674cc2013-04-17 23:02:17 +020013549 assert(!writer->readonly);
Victor Stinner6989ba02013-11-18 21:08:39 +010013550 if (writer->overallocate
13551 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13552 /* overallocate to limit the number of realloc() */
13553 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013554 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013555 if (newlen < writer->min_length)
13556 newlen = writer->min_length;
13557
Victor Stinnerd3f08822012-05-29 12:57:52 +020013558 writer->buffer = PyUnicode_New(newlen, maxchar);
13559 if (writer->buffer == NULL)
13560 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013561 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013562 else if (newlen > writer->size) {
Victor Stinner6989ba02013-11-18 21:08:39 +010013563 if (writer->overallocate
13564 && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
13565 /* overallocate to limit the number of realloc() */
13566 newlen += newlen / OVERALLOCATE_FACTOR;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013567 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013568 if (newlen < writer->min_length)
13569 newlen = writer->min_length;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013570
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013571 if (maxchar > writer->maxchar || writer->readonly) {
Victor Stinner202fdca2012-05-07 12:47:02 +020013572 /* resize + widen */
Serhiy Storchaka28b21e52015-10-02 13:07:28 +030013573 maxchar = Py_MAX(maxchar, writer->maxchar);
Victor Stinner202fdca2012-05-07 12:47:02 +020013574 newbuffer = PyUnicode_New(newlen, maxchar);
13575 if (newbuffer == NULL)
13576 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013577 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13578 writer->buffer, 0, writer->pos);
Victor Stinner202fdca2012-05-07 12:47:02 +020013579 Py_DECREF(writer->buffer);
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013580 writer->readonly = 0;
Victor Stinner202fdca2012-05-07 12:47:02 +020013581 }
13582 else {
13583 newbuffer = resize_compact(writer->buffer, newlen);
13584 if (newbuffer == NULL)
13585 return -1;
13586 }
13587 writer->buffer = newbuffer;
Victor Stinner202fdca2012-05-07 12:47:02 +020013588 }
13589 else if (maxchar > writer->maxchar) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013590 assert(!writer->readonly);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013591 newbuffer = PyUnicode_New(writer->size, maxchar);
13592 if (newbuffer == NULL)
Victor Stinner202fdca2012-05-07 12:47:02 +020013593 return -1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013594 _PyUnicode_FastCopyCharacters(newbuffer, 0,
13595 writer->buffer, 0, writer->pos);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030013596 Py_SETREF(writer->buffer, newbuffer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013597 }
Victor Stinner8f674cc2013-04-17 23:02:17 +020013598 _PyUnicodeWriter_Update(writer);
Victor Stinner202fdca2012-05-07 12:47:02 +020013599 return 0;
Victor Stinner6989ba02013-11-18 21:08:39 +010013600
13601#undef OVERALLOCATE_FACTOR
Victor Stinner202fdca2012-05-07 12:47:02 +020013602}
13603
Victor Stinnerca9381e2015-09-22 00:58:32 +020013604int
13605_PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
13606 enum PyUnicode_Kind kind)
13607{
13608 Py_UCS4 maxchar;
13609
13610 /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
13611 assert(writer->kind < kind);
13612
13613 switch (kind)
13614 {
13615 case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
13616 case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
13617 case PyUnicode_4BYTE_KIND: maxchar = 0x10ffff; break;
13618 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013619 Py_UNREACHABLE();
Victor Stinnerca9381e2015-09-22 00:58:32 +020013620 }
13621
13622 return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
13623}
13624
Benjamin Peterson2e7c5e92016-09-07 15:33:32 -070013625static inline int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013626_PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
Victor Stinnera0dd0212013-04-11 22:09:04 +020013627{
Victor Stinner2740e462016-09-06 16:58:36 -070013628 assert(ch <= MAX_UNICODE);
Victor Stinnera0dd0212013-04-11 22:09:04 +020013629 if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
13630 return -1;
13631 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
13632 writer->pos++;
13633 return 0;
13634}
13635
13636int
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020013637_PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
13638{
13639 return _PyUnicodeWriter_WriteCharInline(writer, ch);
13640}
13641
13642int
Victor Stinnerd3f08822012-05-29 12:57:52 +020013643_PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
13644{
13645 Py_UCS4 maxchar;
13646 Py_ssize_t len;
13647
13648 if (PyUnicode_READY(str) == -1)
13649 return -1;
13650 len = PyUnicode_GET_LENGTH(str);
13651 if (len == 0)
13652 return 0;
13653 maxchar = PyUnicode_MAX_CHAR_VALUE(str);
13654 if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013655 if (writer->buffer == NULL && !writer->overallocate) {
Victor Stinner1912b392015-03-26 09:37:23 +010013656 assert(_PyUnicode_CheckConsistency(str, 1));
Victor Stinner8f674cc2013-04-17 23:02:17 +020013657 writer->readonly = 1;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013658 Py_INCREF(str);
13659 writer->buffer = str;
13660 _PyUnicodeWriter_Update(writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013661 writer->pos += len;
13662 return 0;
13663 }
13664 if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
13665 return -1;
13666 }
13667 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13668 str, 0, len);
13669 writer->pos += len;
13670 return 0;
13671}
13672
Victor Stinnere215d962012-10-06 23:03:36 +020013673int
Victor Stinnercfc4c132013-04-03 01:48:39 +020013674_PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
13675 Py_ssize_t start, Py_ssize_t end)
13676{
13677 Py_UCS4 maxchar;
13678 Py_ssize_t len;
13679
13680 if (PyUnicode_READY(str) == -1)
13681 return -1;
13682
13683 assert(0 <= start);
13684 assert(end <= PyUnicode_GET_LENGTH(str));
13685 assert(start <= end);
13686
13687 if (end == 0)
13688 return 0;
13689
13690 if (start == 0 && end == PyUnicode_GET_LENGTH(str))
13691 return _PyUnicodeWriter_WriteStr(writer, str);
13692
13693 if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
13694 maxchar = _PyUnicode_FindMaxChar(str, start, end);
13695 else
13696 maxchar = writer->maxchar;
13697 len = end - start;
13698
13699 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
13700 return -1;
13701
13702 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
13703 str, start, len);
13704 writer->pos += len;
13705 return 0;
13706}
13707
13708int
Victor Stinner4a587072013-11-19 12:54:53 +010013709_PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
13710 const char *ascii, Py_ssize_t len)
13711{
13712 if (len == -1)
13713 len = strlen(ascii);
13714
13715 assert(ucs1lib_find_max_char((Py_UCS1*)ascii, (Py_UCS1*)ascii + len) < 128);
13716
13717 if (writer->buffer == NULL && !writer->overallocate) {
13718 PyObject *str;
13719
13720 str = _PyUnicode_FromASCII(ascii, len);
13721 if (str == NULL)
13722 return -1;
13723
13724 writer->readonly = 1;
13725 writer->buffer = str;
13726 _PyUnicodeWriter_Update(writer);
13727 writer->pos += len;
13728 return 0;
13729 }
13730
13731 if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
13732 return -1;
13733
13734 switch (writer->kind)
13735 {
13736 case PyUnicode_1BYTE_KIND:
13737 {
13738 const Py_UCS1 *str = (const Py_UCS1 *)ascii;
13739 Py_UCS1 *data = writer->data;
13740
Christian Heimesf051e432016-09-13 20:22:02 +020013741 memcpy(data + writer->pos, str, len);
Victor Stinner4a587072013-11-19 12:54:53 +010013742 break;
13743 }
13744 case PyUnicode_2BYTE_KIND:
13745 {
13746 _PyUnicode_CONVERT_BYTES(
13747 Py_UCS1, Py_UCS2,
13748 ascii, ascii + len,
13749 (Py_UCS2 *)writer->data + writer->pos);
13750 break;
13751 }
13752 case PyUnicode_4BYTE_KIND:
13753 {
13754 _PyUnicode_CONVERT_BYTES(
13755 Py_UCS1, Py_UCS4,
13756 ascii, ascii + len,
13757 (Py_UCS4 *)writer->data + writer->pos);
13758 break;
13759 }
13760 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070013761 Py_UNREACHABLE();
Victor Stinner4a587072013-11-19 12:54:53 +010013762 }
13763
13764 writer->pos += len;
13765 return 0;
13766}
13767
13768int
13769_PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
13770 const char *str, Py_ssize_t len)
Victor Stinnere215d962012-10-06 23:03:36 +020013771{
13772 Py_UCS4 maxchar;
13773
13774 maxchar = ucs1lib_find_max_char((Py_UCS1*)str, (Py_UCS1*)str + len);
13775 if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
13776 return -1;
13777 unicode_write_cstr(writer->buffer, writer->pos, str, len);
13778 writer->pos += len;
13779 return 0;
13780}
13781
Victor Stinnerd3f08822012-05-29 12:57:52 +020013782PyObject *
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013783_PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013784{
Victor Stinner15a0bd32013-07-08 22:29:55 +020013785 PyObject *str;
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013786
Victor Stinnerd3f08822012-05-29 12:57:52 +020013787 if (writer->pos == 0) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013788 Py_CLEAR(writer->buffer);
Serhiy Storchaka678db842013-01-26 12:16:36 +020013789 _Py_RETURN_UNICODE_EMPTY();
Victor Stinnerd3f08822012-05-29 12:57:52 +020013790 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013791
13792 str = writer->buffer;
13793 writer->buffer = NULL;
13794
Victor Stinnerd7b7c742012-06-04 22:52:12 +020013795 if (writer->readonly) {
Victor Stinner9e6b4d72013-07-09 00:37:24 +020013796 assert(PyUnicode_GET_LENGTH(str) == writer->pos);
13797 return str;
Victor Stinnerd3f08822012-05-29 12:57:52 +020013798 }
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013799
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013800 if (PyUnicode_GET_LENGTH(str) != writer->pos) {
13801 PyObject *str2;
13802 str2 = resize_compact(str, writer->pos);
13803 if (str2 == NULL) {
13804 Py_DECREF(str);
13805 return NULL;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013806 }
Serhiy Storchakac8bc3d12016-10-25 13:23:56 +030013807 str = str2;
Victor Stinner6c2cdae2015-10-12 13:29:43 +020013808 }
13809
Victor Stinner15a0bd32013-07-08 22:29:55 +020013810 assert(_PyUnicode_CheckConsistency(str, 1));
13811 return unicode_result_ready(str);
Victor Stinner202fdca2012-05-07 12:47:02 +020013812}
13813
Victor Stinnerd3f08822012-05-29 12:57:52 +020013814void
Victor Stinner3b1a74a2012-05-09 22:25:00 +020013815_PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
Victor Stinner202fdca2012-05-07 12:47:02 +020013816{
13817 Py_CLEAR(writer->buffer);
13818}
13819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013820#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000013821
13822PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013823 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000013824\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013825Return a formatted version of S, using substitutions from args and kwargs.\n\
13826The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000013827
Eric Smith27bbca62010-11-04 17:06:58 +000013828PyDoc_STRVAR(format_map__doc__,
13829 "S.format_map(mapping) -> str\n\
13830\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000013831Return a formatted version of S, using substitutions from mapping.\n\
13832The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000013833
INADA Naoki3ae20562017-01-16 20:41:20 +090013834/*[clinic input]
13835str.__format__ as unicode___format__
13836
13837 format_spec: unicode
13838 /
13839
13840Return a formatted version of the string as described by format_spec.
13841[clinic start generated code]*/
13842
Eric Smith4a7d76d2008-05-30 18:10:19 +000013843static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013844unicode___format___impl(PyObject *self, PyObject *format_spec)
INADA Naoki15f94592017-01-16 21:49:13 +090013845/*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
Eric Smith4a7d76d2008-05-30 18:10:19 +000013846{
Victor Stinnerd3f08822012-05-29 12:57:52 +020013847 _PyUnicodeWriter writer;
13848 int ret;
Eric Smith4a7d76d2008-05-30 18:10:19 +000013849
Victor Stinnerd3f08822012-05-29 12:57:52 +020013850 if (PyUnicode_READY(self) == -1)
13851 return NULL;
Victor Stinner8f674cc2013-04-17 23:02:17 +020013852 _PyUnicodeWriter_Init(&writer);
Victor Stinnerd3f08822012-05-29 12:57:52 +020013853 ret = _PyUnicode_FormatAdvancedWriter(&writer,
13854 self, format_spec, 0,
13855 PyUnicode_GET_LENGTH(format_spec));
13856 if (ret == -1) {
13857 _PyUnicodeWriter_Dealloc(&writer);
13858 return NULL;
13859 }
13860 return _PyUnicodeWriter_Finish(&writer);
Eric Smith4a7d76d2008-05-30 18:10:19 +000013861}
13862
INADA Naoki3ae20562017-01-16 20:41:20 +090013863/*[clinic input]
13864str.__sizeof__ as unicode_sizeof
13865
13866Return the size of the string in memory, in bytes.
13867[clinic start generated code]*/
Eric Smith8c663262007-08-25 02:26:07 +000013868
13869static PyObject *
INADA Naoki3ae20562017-01-16 20:41:20 +090013870unicode_sizeof_impl(PyObject *self)
13871/*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013872{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013873 Py_ssize_t size;
13874
13875 /* If it's a compact object, account for base structure +
13876 character data. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013877 if (PyUnicode_IS_COMPACT_ASCII(self))
13878 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
13879 else if (PyUnicode_IS_COMPACT(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013880 size = sizeof(PyCompactUnicodeObject) +
INADA Naoki3ae20562017-01-16 20:41:20 +090013881 (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013882 else {
13883 /* If it is a two-block object, account for base object, and
13884 for character block if present. */
13885 size = sizeof(PyUnicodeObject);
INADA Naoki3ae20562017-01-16 20:41:20 +090013886 if (_PyUnicode_DATA_ANY(self))
13887 size += (PyUnicode_GET_LENGTH(self) + 1) *
13888 PyUnicode_KIND(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013889 }
13890 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013891 with the data pointer. Check if the data is not shared. */
INADA Naoki3ae20562017-01-16 20:41:20 +090013892 if (_PyUnicode_HAS_WSTR_MEMORY(self))
13893 size += (PyUnicode_WSTR_LENGTH(self) + 1) * sizeof(wchar_t);
13894 if (_PyUnicode_HAS_UTF8_MEMORY(self))
13895 size += PyUnicode_UTF8_LENGTH(self) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013896
13897 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013898}
13899
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013900static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013901unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013902{
Victor Stinnerbf6e5602011-12-12 01:53:47 +010013903 PyObject *copy = _PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013904 if (!copy)
13905 return NULL;
13906 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013907}
13908
Guido van Rossumd57fd912000-03-10 22:53:23 +000013909static PyMethodDef unicode_methods[] = {
INADA Naoki3ae20562017-01-16 20:41:20 +090013910 UNICODE_ENCODE_METHODDEF
13911 UNICODE_REPLACE_METHODDEF
13912 UNICODE_SPLIT_METHODDEF
13913 UNICODE_RSPLIT_METHODDEF
13914 UNICODE_JOIN_METHODDEF
13915 UNICODE_CAPITALIZE_METHODDEF
13916 UNICODE_CASEFOLD_METHODDEF
13917 UNICODE_TITLE_METHODDEF
13918 UNICODE_CENTER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013919 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013920 UNICODE_EXPANDTABS_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013921 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013922 UNICODE_PARTITION_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013923 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013924 UNICODE_LJUST_METHODDEF
13925 UNICODE_LOWER_METHODDEF
13926 UNICODE_LSTRIP_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013927 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13928 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013929 UNICODE_RJUST_METHODDEF
13930 UNICODE_RSTRIP_METHODDEF
13931 UNICODE_RPARTITION_METHODDEF
13932 UNICODE_SPLITLINES_METHODDEF
13933 UNICODE_STRIP_METHODDEF
13934 UNICODE_SWAPCASE_METHODDEF
13935 UNICODE_TRANSLATE_METHODDEF
13936 UNICODE_UPPER_METHODDEF
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013937 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13938 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
INADA Naokia49ac992018-01-27 14:06:21 +090013939 UNICODE_ISASCII_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013940 UNICODE_ISLOWER_METHODDEF
13941 UNICODE_ISUPPER_METHODDEF
13942 UNICODE_ISTITLE_METHODDEF
13943 UNICODE_ISSPACE_METHODDEF
13944 UNICODE_ISDECIMAL_METHODDEF
13945 UNICODE_ISDIGIT_METHODDEF
13946 UNICODE_ISNUMERIC_METHODDEF
13947 UNICODE_ISALPHA_METHODDEF
13948 UNICODE_ISALNUM_METHODDEF
13949 UNICODE_ISIDENTIFIER_METHODDEF
13950 UNICODE_ISPRINTABLE_METHODDEF
13951 UNICODE_ZFILL_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013952 {"format", (PyCFunction)(void(*)(void)) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013953 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
INADA Naoki3ae20562017-01-16 20:41:20 +090013954 UNICODE___FORMAT___METHODDEF
Larry Hastings31826802013-10-19 00:09:25 -070013955 UNICODE_MAKETRANS_METHODDEF
INADA Naoki3ae20562017-01-16 20:41:20 +090013956 UNICODE_SIZEOF_METHODDEF
Walter Dörwald068325e2002-04-15 13:36:47 +000013957#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013958 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013959 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013960#endif
13961
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053013962 {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013963 {NULL, NULL}
13964};
13965
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013966static PyObject *
13967unicode_mod(PyObject *v, PyObject *w)
13968{
Brian Curtindfc80e32011-08-10 20:28:54 -050013969 if (!PyUnicode_Check(v))
13970 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013971 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013972}
13973
13974static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013975 0, /*nb_add*/
13976 0, /*nb_subtract*/
13977 0, /*nb_multiply*/
13978 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013979};
13980
Guido van Rossumd57fd912000-03-10 22:53:23 +000013981static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013982 (lenfunc) unicode_length, /* sq_length */
13983 PyUnicode_Concat, /* sq_concat */
13984 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13985 (ssizeargfunc) unicode_getitem, /* sq_item */
13986 0, /* sq_slice */
13987 0, /* sq_ass_item */
13988 0, /* sq_ass_slice */
13989 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013990};
13991
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013992static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013993unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013994{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013995 if (PyUnicode_READY(self) == -1)
13996 return NULL;
13997
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013998 if (PyIndex_Check(item)) {
13999 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014000 if (i == -1 && PyErr_Occurred())
14001 return NULL;
14002 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014003 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014004 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014005 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000014006 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014007 PyObject *result;
14008 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014009 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014010 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014011
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014012 if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014013 return NULL;
14014 }
Serhiy Storchakab879fe82017-04-08 09:53:51 +030014015 slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
14016 &start, &stop, step);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014017
14018 if (slicelength <= 0) {
Serhiy Storchaka678db842013-01-26 12:16:36 +020014019 _Py_RETURN_UNICODE_EMPTY();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014020 } else if (start == 0 && step == 1 &&
Victor Stinnerc4b49542011-12-11 22:44:26 +010014021 slicelength == PyUnicode_GET_LENGTH(self)) {
14022 return unicode_result_unchanged(self);
Thomas Woutersed03b412007-08-28 21:37:11 +000014023 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014024 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020014025 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014026 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014027 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014028 src_kind = PyUnicode_KIND(self);
14029 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020014030 if (!PyUnicode_IS_ASCII(self)) {
14031 kind_limit = kind_maxchar_limit(src_kind);
14032 max_char = 0;
14033 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
14034 ch = PyUnicode_READ(src_kind, src_data, cur);
14035 if (ch > max_char) {
14036 max_char = ch;
14037 if (max_char >= kind_limit)
14038 break;
14039 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020014040 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014041 }
Victor Stinner55c99112011-10-13 01:17:06 +020014042 else
14043 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014044 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014045 if (result == NULL)
14046 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014047 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014048 dest_data = PyUnicode_DATA(result);
14049
14050 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020014051 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
14052 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014053 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020014054 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020014055 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014056 } else {
14057 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
14058 return NULL;
14059 }
14060}
14061
14062static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 (lenfunc)unicode_length, /* mp_length */
14064 (binaryfunc)unicode_subscript, /* mp_subscript */
14065 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000014066};
14067
Guido van Rossumd57fd912000-03-10 22:53:23 +000014068
Guido van Rossumd57fd912000-03-10 22:53:23 +000014069/* Helpers for PyUnicode_Format() */
14070
Victor Stinnera47082312012-10-04 02:19:54 +020014071struct unicode_formatter_t {
14072 PyObject *args;
14073 int args_owned;
14074 Py_ssize_t arglen, argidx;
14075 PyObject *dict;
14076
14077 enum PyUnicode_Kind fmtkind;
14078 Py_ssize_t fmtcnt, fmtpos;
14079 void *fmtdata;
14080 PyObject *fmtstr;
14081
14082 _PyUnicodeWriter writer;
14083};
14084
14085struct unicode_format_arg_t {
14086 Py_UCS4 ch;
14087 int flags;
14088 Py_ssize_t width;
14089 int prec;
14090 int sign;
14091};
14092
Guido van Rossumd57fd912000-03-10 22:53:23 +000014093static PyObject *
Victor Stinnera47082312012-10-04 02:19:54 +020014094unicode_format_getnextarg(struct unicode_formatter_t *ctx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014095{
Victor Stinnera47082312012-10-04 02:19:54 +020014096 Py_ssize_t argidx = ctx->argidx;
14097
14098 if (argidx < ctx->arglen) {
14099 ctx->argidx++;
14100 if (ctx->arglen < 0)
14101 return ctx->args;
Benjamin Peterson29060642009-01-31 22:14:21 +000014102 else
Victor Stinnera47082312012-10-04 02:19:54 +020014103 return PyTuple_GetItem(ctx->args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000014104 }
14105 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014106 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000014107 return NULL;
14108}
14109
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014110/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000014111
Victor Stinnera47082312012-10-04 02:19:54 +020014112/* Format a float into the writer if the writer is not NULL, or into *p_output
14113 otherwise.
14114
14115 Return 0 on success, raise an exception and return -1 on error. */
Victor Stinnerd3f08822012-05-29 12:57:52 +020014116static int
Victor Stinnera47082312012-10-04 02:19:54 +020014117formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
14118 PyObject **p_output,
14119 _PyUnicodeWriter *writer)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014120{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014121 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014122 double x;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014123 Py_ssize_t len;
Victor Stinnera47082312012-10-04 02:19:54 +020014124 int prec;
14125 int dtoa_flags;
Tim Petersced69f82003-09-16 20:30:58 +000014126
Guido van Rossumd57fd912000-03-10 22:53:23 +000014127 x = PyFloat_AsDouble(v);
14128 if (x == -1.0 && PyErr_Occurred())
Victor Stinnerd3f08822012-05-29 12:57:52 +020014129 return -1;
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014130
Victor Stinnera47082312012-10-04 02:19:54 +020014131 prec = arg->prec;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014132 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014133 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000014134
Victor Stinnera47082312012-10-04 02:19:54 +020014135 if (arg->flags & F_ALT)
14136 dtoa_flags = Py_DTSF_ALT;
14137 else
14138 dtoa_flags = 0;
14139 p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000014140 if (p == NULL)
Victor Stinnerd3f08822012-05-29 12:57:52 +020014141 return -1;
14142 len = strlen(p);
14143 if (writer) {
Victor Stinner4a587072013-11-19 12:54:53 +010014144 if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
Christian Heimesf4f99392012-09-10 11:48:41 +020014145 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014146 return -1;
Christian Heimesf4f99392012-09-10 11:48:41 +020014147 }
Victor Stinnerd3f08822012-05-29 12:57:52 +020014148 }
14149 else
14150 *p_output = _PyUnicode_FromASCII(p, len);
Eric Smith0923d1d2009-04-16 20:16:10 +000014151 PyMem_Free(p);
Victor Stinnerd3f08822012-05-29 12:57:52 +020014152 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014153}
14154
Victor Stinnerd0880d52012-04-27 23:40:13 +020014155/* formatlong() emulates the format codes d, u, o, x and X, and
14156 * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
14157 * Python's regular ints.
14158 * Return value: a new PyUnicodeObject*, or NULL if error.
14159 * The output string is of the form
14160 * "-"? ("0x" | "0X")? digit+
14161 * "0x"/"0X" are present only for x and X conversions, with F_ALT
14162 * set in flags. The case of hex digits will be correct,
14163 * There will be at least prec digits, zero-filled on the left if
14164 * necessary to get that many.
14165 * val object to be converted
14166 * flags bitmask of format flags; only F_ALT is looked at
14167 * prec minimum number of digits; 0-fill on left if needed
14168 * type a character in [duoxX]; u acts the same as d
14169 *
14170 * CAUTION: o, x and X conversions on regular ints can never
14171 * produce a '-' sign, but can for Python's unbounded ints.
14172 */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014173PyObject *
14174_PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
Tim Peters38fd5b62000-09-21 05:43:11 +000014175{
Victor Stinnerd0880d52012-04-27 23:40:13 +020014176 PyObject *result = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014177 char *buf;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014178 Py_ssize_t i;
14179 int sign; /* 1 if '-', else 0 */
14180 int len; /* number of characters */
14181 Py_ssize_t llen;
14182 int numdigits; /* len == numnondigits + numdigits */
14183 int numnondigits = 0;
Tim Peters38fd5b62000-09-21 05:43:11 +000014184
Victor Stinnerd0880d52012-04-27 23:40:13 +020014185 /* Avoid exceeding SSIZE_T_MAX */
14186 if (prec > INT_MAX-3) {
14187 PyErr_SetString(PyExc_OverflowError,
14188 "precision too large");
Benjamin Peterson14339b62009-01-31 16:36:08 +000014189 return NULL;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014190 }
14191
14192 assert(PyLong_Check(val));
14193
14194 switch (type) {
Victor Stinner621ef3d2012-10-02 00:33:47 +020014195 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014196 Py_UNREACHABLE();
Victor Stinnerd0880d52012-04-27 23:40:13 +020014197 case 'd':
Victor Stinner621ef3d2012-10-02 00:33:47 +020014198 case 'i':
Victor Stinnerd0880d52012-04-27 23:40:13 +020014199 case 'u':
Ethan Furmanfb137212013-08-31 10:18:55 -070014200 /* int and int subclasses should print numerically when a numeric */
14201 /* format code is used (see issue18780) */
14202 result = PyNumber_ToBase(val, 10);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014203 break;
14204 case 'o':
14205 numnondigits = 2;
14206 result = PyNumber_ToBase(val, 8);
14207 break;
14208 case 'x':
14209 case 'X':
14210 numnondigits = 2;
14211 result = PyNumber_ToBase(val, 16);
14212 break;
Victor Stinnerd0880d52012-04-27 23:40:13 +020014213 }
14214 if (!result)
14215 return NULL;
14216
14217 assert(unicode_modifiable(result));
14218 assert(PyUnicode_IS_READY(result));
14219 assert(PyUnicode_IS_ASCII(result));
14220
14221 /* To modify the string in-place, there can only be one reference. */
14222 if (Py_REFCNT(result) != 1) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014223 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014224 PyErr_BadInternalCall();
14225 return NULL;
14226 }
14227 buf = PyUnicode_DATA(result);
14228 llen = PyUnicode_GET_LENGTH(result);
14229 if (llen > INT_MAX) {
Christian Heimesd47802e2013-06-29 21:33:36 +020014230 Py_DECREF(result);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014231 PyErr_SetString(PyExc_ValueError,
Ethan Furmanb95b5612015-01-23 20:05:18 -080014232 "string too large in _PyUnicode_FormatLong");
Victor Stinnerd0880d52012-04-27 23:40:13 +020014233 return NULL;
14234 }
14235 len = (int)llen;
14236 sign = buf[0] == '-';
14237 numnondigits += sign;
14238 numdigits = len - numnondigits;
14239 assert(numdigits > 0);
14240
14241 /* Get rid of base marker unless F_ALT */
Ethan Furmanb95b5612015-01-23 20:05:18 -080014242 if (((alt) == 0 &&
Victor Stinnerd0880d52012-04-27 23:40:13 +020014243 (type == 'o' || type == 'x' || type == 'X'))) {
14244 assert(buf[sign] == '0');
14245 assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
14246 buf[sign+1] == 'o');
14247 numnondigits -= 2;
14248 buf += 2;
14249 len -= 2;
14250 if (sign)
14251 buf[0] = '-';
14252 assert(len == numnondigits + numdigits);
14253 assert(numdigits > 0);
14254 }
14255
14256 /* Fill with leading zeroes to meet minimum width. */
14257 if (prec > numdigits) {
14258 PyObject *r1 = PyBytes_FromStringAndSize(NULL,
14259 numnondigits + prec);
14260 char *b1;
14261 if (!r1) {
14262 Py_DECREF(result);
14263 return NULL;
14264 }
14265 b1 = PyBytes_AS_STRING(r1);
14266 for (i = 0; i < numnondigits; ++i)
14267 *b1++ = *buf++;
14268 for (i = 0; i < prec - numdigits; i++)
14269 *b1++ = '0';
14270 for (i = 0; i < numdigits; i++)
14271 *b1++ = *buf++;
14272 *b1 = '\0';
14273 Py_DECREF(result);
14274 result = r1;
14275 buf = PyBytes_AS_STRING(result);
14276 len = numnondigits + prec;
14277 }
14278
14279 /* Fix up case for hex conversions. */
14280 if (type == 'X') {
14281 /* Need to convert all lower case letters to upper case.
14282 and need to convert 0x to 0X (and -0x to -0X). */
14283 for (i = 0; i < len; i++)
14284 if (buf[i] >= 'a' && buf[i] <= 'x')
14285 buf[i] -= 'a'-'A';
14286 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014287 if (!PyUnicode_Check(result)
14288 || buf != PyUnicode_DATA(result)) {
Victor Stinnerd0880d52012-04-27 23:40:13 +020014289 PyObject *unicode;
Victor Stinnerd3f08822012-05-29 12:57:52 +020014290 unicode = _PyUnicode_FromASCII(buf, len);
Victor Stinnerd0880d52012-04-27 23:40:13 +020014291 Py_DECREF(result);
14292 result = unicode;
14293 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014294 else if (len != PyUnicode_GET_LENGTH(result)) {
14295 if (PyUnicode_Resize(&result, len) < 0)
14296 Py_CLEAR(result);
14297 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000014298 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000014299}
14300
Ethan Furmandf3ed242014-01-05 06:50:30 -080014301/* Format an integer or a float as an integer.
Victor Stinner621ef3d2012-10-02 00:33:47 +020014302 * Return 1 if the number has been formatted into the writer,
Victor Stinnera47082312012-10-04 02:19:54 +020014303 * 0 if the number has been formatted into *p_output
Victor Stinner621ef3d2012-10-02 00:33:47 +020014304 * -1 and raise an exception on error */
14305static int
Victor Stinnera47082312012-10-04 02:19:54 +020014306mainformatlong(PyObject *v,
14307 struct unicode_format_arg_t *arg,
14308 PyObject **p_output,
14309 _PyUnicodeWriter *writer)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014310{
14311 PyObject *iobj, *res;
Victor Stinnera47082312012-10-04 02:19:54 +020014312 char type = (char)arg->ch;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014313
14314 if (!PyNumber_Check(v))
14315 goto wrongtype;
14316
Ethan Furman9ab74802014-03-21 06:38:46 -070014317 /* make sure number is a type of integer for o, x, and X */
Victor Stinner621ef3d2012-10-02 00:33:47 +020014318 if (!PyLong_Check(v)) {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014319 if (type == 'o' || type == 'x' || type == 'X') {
14320 iobj = PyNumber_Index(v);
14321 if (iobj == NULL) {
Ethan Furman9ab74802014-03-21 06:38:46 -070014322 if (PyErr_ExceptionMatches(PyExc_TypeError))
14323 goto wrongtype;
Ethan Furman38d872e2014-03-19 08:38:52 -070014324 return -1;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014325 }
14326 }
14327 else {
14328 iobj = PyNumber_Long(v);
14329 if (iobj == NULL ) {
14330 if (PyErr_ExceptionMatches(PyExc_TypeError))
14331 goto wrongtype;
14332 return -1;
14333 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014334 }
14335 assert(PyLong_Check(iobj));
14336 }
14337 else {
14338 iobj = v;
14339 Py_INCREF(iobj);
14340 }
14341
14342 if (PyLong_CheckExact(v)
Victor Stinnera47082312012-10-04 02:19:54 +020014343 && arg->width == -1 && arg->prec == -1
14344 && !(arg->flags & (F_SIGN | F_BLANK))
14345 && type != 'X')
Victor Stinner621ef3d2012-10-02 00:33:47 +020014346 {
14347 /* Fast path */
Victor Stinnera47082312012-10-04 02:19:54 +020014348 int alternate = arg->flags & F_ALT;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014349 int base;
14350
Victor Stinnera47082312012-10-04 02:19:54 +020014351 switch(type)
Victor Stinner621ef3d2012-10-02 00:33:47 +020014352 {
14353 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070014354 Py_UNREACHABLE();
Victor Stinner621ef3d2012-10-02 00:33:47 +020014355 case 'd':
14356 case 'i':
14357 case 'u':
14358 base = 10;
14359 break;
14360 case 'o':
14361 base = 8;
14362 break;
14363 case 'x':
14364 case 'X':
14365 base = 16;
14366 break;
14367 }
14368
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014369 if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
14370 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014371 return -1;
Victor Stinnerc89d28f2012-10-02 12:54:07 +020014372 }
14373 Py_DECREF(iobj);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014374 return 1;
14375 }
14376
Ethan Furmanb95b5612015-01-23 20:05:18 -080014377 res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
Victor Stinner621ef3d2012-10-02 00:33:47 +020014378 Py_DECREF(iobj);
14379 if (res == NULL)
14380 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014381 *p_output = res;
Victor Stinner621ef3d2012-10-02 00:33:47 +020014382 return 0;
14383
14384wrongtype:
Ethan Furman9ab74802014-03-21 06:38:46 -070014385 switch(type)
14386 {
14387 case 'o':
14388 case 'x':
14389 case 'X':
14390 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014391 "%%%c format: an integer is required, "
14392 "not %.200s",
14393 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014394 break;
14395 default:
14396 PyErr_Format(PyExc_TypeError,
Victor Stinner998b8062018-09-12 00:23:25 +020014397 "%%%c format: a number is required, "
14398 "not %.200s",
14399 type, Py_TYPE(v)->tp_name);
Ethan Furman9ab74802014-03-21 06:38:46 -070014400 break;
14401 }
Victor Stinner621ef3d2012-10-02 00:33:47 +020014402 return -1;
14403}
14404
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014405static Py_UCS4
14406formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014407{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014408 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014409 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014410 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014411 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000014412 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014413 goto onError;
14414 }
14415 else {
Ethan Furmandf3ed242014-01-05 06:50:30 -080014416 PyObject *iobj;
Benjamin Peterson29060642009-01-31 22:14:21 +000014417 long x;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014418 /* make sure number is a type of integer */
14419 if (!PyLong_Check(v)) {
14420 iobj = PyNumber_Index(v);
14421 if (iobj == NULL) {
Ethan Furman38d872e2014-03-19 08:38:52 -070014422 goto onError;
Ethan Furmandf3ed242014-01-05 06:50:30 -080014423 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014424 x = PyLong_AsLong(iobj);
Ethan Furmandf3ed242014-01-05 06:50:30 -080014425 Py_DECREF(iobj);
14426 }
Xiang Zhangea1cf872016-12-22 15:30:47 +080014427 else {
14428 x = PyLong_AsLong(v);
14429 }
Benjamin Peterson29060642009-01-31 22:14:21 +000014430 if (x == -1 && PyErr_Occurred())
14431 goto onError;
14432
Victor Stinner8faf8212011-12-08 22:14:11 +010014433 if (x < 0 || x > MAX_UNICODE) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014434 PyErr_SetString(PyExc_OverflowError,
14435 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014436 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000014437 }
14438
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014439 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014440 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000014441
Benjamin Peterson29060642009-01-31 22:14:21 +000014442 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000014443 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000014444 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020014445 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014446}
14447
Victor Stinnera47082312012-10-04 02:19:54 +020014448/* Parse options of an argument: flags, width, precision.
14449 Handle also "%(name)" syntax.
14450
14451 Return 0 if the argument has been formatted into arg->str.
14452 Return 1 if the argument has been written into ctx->writer,
14453 Raise an exception and return -1 on error. */
14454static int
14455unicode_format_arg_parse(struct unicode_formatter_t *ctx,
14456 struct unicode_format_arg_t *arg)
14457{
14458#define FORMAT_READ(ctx) \
14459 PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
14460
14461 PyObject *v;
14462
Victor Stinnera47082312012-10-04 02:19:54 +020014463 if (arg->ch == '(') {
14464 /* Get argument value from a dictionary. Example: "%(name)s". */
14465 Py_ssize_t keystart;
14466 Py_ssize_t keylen;
14467 PyObject *key;
14468 int pcount = 1;
14469
14470 if (ctx->dict == NULL) {
14471 PyErr_SetString(PyExc_TypeError,
14472 "format requires a mapping");
14473 return -1;
14474 }
14475 ++ctx->fmtpos;
14476 --ctx->fmtcnt;
14477 keystart = ctx->fmtpos;
14478 /* Skip over balanced parentheses */
14479 while (pcount > 0 && --ctx->fmtcnt >= 0) {
14480 arg->ch = FORMAT_READ(ctx);
14481 if (arg->ch == ')')
14482 --pcount;
14483 else if (arg->ch == '(')
14484 ++pcount;
14485 ctx->fmtpos++;
14486 }
14487 keylen = ctx->fmtpos - keystart - 1;
14488 if (ctx->fmtcnt < 0 || pcount > 0) {
14489 PyErr_SetString(PyExc_ValueError,
14490 "incomplete format key");
14491 return -1;
14492 }
14493 key = PyUnicode_Substring(ctx->fmtstr,
14494 keystart, keystart + keylen);
14495 if (key == NULL)
14496 return -1;
14497 if (ctx->args_owned) {
Victor Stinnera47082312012-10-04 02:19:54 +020014498 ctx->args_owned = 0;
Serhiy Storchaka191321d2015-12-27 15:41:34 +020014499 Py_DECREF(ctx->args);
Victor Stinnera47082312012-10-04 02:19:54 +020014500 }
14501 ctx->args = PyObject_GetItem(ctx->dict, key);
14502 Py_DECREF(key);
14503 if (ctx->args == NULL)
14504 return -1;
14505 ctx->args_owned = 1;
14506 ctx->arglen = -1;
14507 ctx->argidx = -2;
14508 }
14509
14510 /* Parse flags. Example: "%+i" => flags=F_SIGN. */
Victor Stinnera47082312012-10-04 02:19:54 +020014511 while (--ctx->fmtcnt >= 0) {
14512 arg->ch = FORMAT_READ(ctx);
14513 ctx->fmtpos++;
14514 switch (arg->ch) {
14515 case '-': arg->flags |= F_LJUST; continue;
14516 case '+': arg->flags |= F_SIGN; continue;
14517 case ' ': arg->flags |= F_BLANK; continue;
14518 case '#': arg->flags |= F_ALT; continue;
14519 case '0': arg->flags |= F_ZERO; continue;
14520 }
14521 break;
14522 }
14523
14524 /* Parse width. Example: "%10s" => width=10 */
Victor Stinnera47082312012-10-04 02:19:54 +020014525 if (arg->ch == '*') {
14526 v = unicode_format_getnextarg(ctx);
14527 if (v == NULL)
14528 return -1;
14529 if (!PyLong_Check(v)) {
14530 PyErr_SetString(PyExc_TypeError,
14531 "* wants int");
14532 return -1;
14533 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014534 arg->width = PyLong_AsSsize_t(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014535 if (arg->width == -1 && PyErr_Occurred())
14536 return -1;
14537 if (arg->width < 0) {
14538 arg->flags |= F_LJUST;
14539 arg->width = -arg->width;
14540 }
14541 if (--ctx->fmtcnt >= 0) {
14542 arg->ch = FORMAT_READ(ctx);
14543 ctx->fmtpos++;
14544 }
14545 }
14546 else if (arg->ch >= '0' && arg->ch <= '9') {
14547 arg->width = arg->ch - '0';
14548 while (--ctx->fmtcnt >= 0) {
14549 arg->ch = FORMAT_READ(ctx);
14550 ctx->fmtpos++;
14551 if (arg->ch < '0' || arg->ch > '9')
14552 break;
14553 /* Since arg->ch is unsigned, the RHS would end up as unsigned,
14554 mixing signed and unsigned comparison. Since arg->ch is between
14555 '0' and '9', casting to int is safe. */
14556 if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
14557 PyErr_SetString(PyExc_ValueError,
14558 "width too big");
14559 return -1;
14560 }
14561 arg->width = arg->width*10 + (arg->ch - '0');
14562 }
14563 }
14564
14565 /* Parse precision. Example: "%.3f" => prec=3 */
Victor Stinnera47082312012-10-04 02:19:54 +020014566 if (arg->ch == '.') {
14567 arg->prec = 0;
14568 if (--ctx->fmtcnt >= 0) {
14569 arg->ch = FORMAT_READ(ctx);
14570 ctx->fmtpos++;
14571 }
14572 if (arg->ch == '*') {
14573 v = unicode_format_getnextarg(ctx);
14574 if (v == NULL)
14575 return -1;
14576 if (!PyLong_Check(v)) {
14577 PyErr_SetString(PyExc_TypeError,
14578 "* wants int");
14579 return -1;
14580 }
Serhiy Storchaka78980432013-01-15 01:12:17 +020014581 arg->prec = _PyLong_AsInt(v);
Victor Stinnera47082312012-10-04 02:19:54 +020014582 if (arg->prec == -1 && PyErr_Occurred())
14583 return -1;
14584 if (arg->prec < 0)
14585 arg->prec = 0;
14586 if (--ctx->fmtcnt >= 0) {
14587 arg->ch = FORMAT_READ(ctx);
14588 ctx->fmtpos++;
14589 }
14590 }
14591 else if (arg->ch >= '0' && arg->ch <= '9') {
14592 arg->prec = arg->ch - '0';
14593 while (--ctx->fmtcnt >= 0) {
14594 arg->ch = FORMAT_READ(ctx);
14595 ctx->fmtpos++;
14596 if (arg->ch < '0' || arg->ch > '9')
14597 break;
14598 if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
14599 PyErr_SetString(PyExc_ValueError,
Victor Stinner3921e902012-10-06 23:05:00 +020014600 "precision too big");
Victor Stinnera47082312012-10-04 02:19:54 +020014601 return -1;
14602 }
14603 arg->prec = arg->prec*10 + (arg->ch - '0');
14604 }
14605 }
14606 }
14607
14608 /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
14609 if (ctx->fmtcnt >= 0) {
14610 if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
14611 if (--ctx->fmtcnt >= 0) {
14612 arg->ch = FORMAT_READ(ctx);
14613 ctx->fmtpos++;
14614 }
14615 }
14616 }
14617 if (ctx->fmtcnt < 0) {
14618 PyErr_SetString(PyExc_ValueError,
14619 "incomplete format");
14620 return -1;
14621 }
14622 return 0;
14623
14624#undef FORMAT_READ
14625}
14626
14627/* Format one argument. Supported conversion specifiers:
14628
14629 - "s", "r", "a": any type
Ethan Furmandf3ed242014-01-05 06:50:30 -080014630 - "i", "d", "u": int or float
14631 - "o", "x", "X": int
Victor Stinnera47082312012-10-04 02:19:54 +020014632 - "e", "E", "f", "F", "g", "G": float
14633 - "c": int or str (1 character)
14634
Victor Stinner8dbd4212012-12-04 09:30:24 +010014635 When possible, the output is written directly into the Unicode writer
14636 (ctx->writer). A string is created when padding is required.
14637
Victor Stinnera47082312012-10-04 02:19:54 +020014638 Return 0 if the argument has been formatted into *p_str,
14639 1 if the argument has been written into ctx->writer,
Victor Stinner8dbd4212012-12-04 09:30:24 +010014640 -1 on error. */
Victor Stinnera47082312012-10-04 02:19:54 +020014641static int
14642unicode_format_arg_format(struct unicode_formatter_t *ctx,
14643 struct unicode_format_arg_t *arg,
14644 PyObject **p_str)
14645{
14646 PyObject *v;
14647 _PyUnicodeWriter *writer = &ctx->writer;
14648
14649 if (ctx->fmtcnt == 0)
14650 ctx->writer.overallocate = 0;
14651
Victor Stinnera47082312012-10-04 02:19:54 +020014652 v = unicode_format_getnextarg(ctx);
14653 if (v == NULL)
14654 return -1;
14655
Victor Stinnera47082312012-10-04 02:19:54 +020014656
14657 switch (arg->ch) {
Victor Stinnera47082312012-10-04 02:19:54 +020014658 case 's':
14659 case 'r':
14660 case 'a':
14661 if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
14662 /* Fast path */
14663 if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
14664 return -1;
14665 return 1;
14666 }
14667
14668 if (PyUnicode_CheckExact(v) && arg->ch == 's') {
14669 *p_str = v;
14670 Py_INCREF(*p_str);
14671 }
14672 else {
14673 if (arg->ch == 's')
14674 *p_str = PyObject_Str(v);
14675 else if (arg->ch == 'r')
14676 *p_str = PyObject_Repr(v);
14677 else
14678 *p_str = PyObject_ASCII(v);
14679 }
14680 break;
14681
14682 case 'i':
14683 case 'd':
14684 case 'u':
14685 case 'o':
14686 case 'x':
14687 case 'X':
14688 {
14689 int ret = mainformatlong(v, arg, p_str, writer);
14690 if (ret != 0)
14691 return ret;
14692 arg->sign = 1;
14693 break;
14694 }
14695
14696 case 'e':
14697 case 'E':
14698 case 'f':
14699 case 'F':
14700 case 'g':
14701 case 'G':
14702 if (arg->width == -1 && arg->prec == -1
14703 && !(arg->flags & (F_SIGN | F_BLANK)))
14704 {
14705 /* Fast path */
14706 if (formatfloat(v, arg, NULL, writer) == -1)
14707 return -1;
14708 return 1;
14709 }
14710
14711 arg->sign = 1;
14712 if (formatfloat(v, arg, p_str, NULL) == -1)
14713 return -1;
14714 break;
14715
14716 case 'c':
14717 {
14718 Py_UCS4 ch = formatchar(v);
14719 if (ch == (Py_UCS4) -1)
14720 return -1;
14721 if (arg->width == -1 && arg->prec == -1) {
14722 /* Fast path */
Victor Stinner8a1a6cf2013-04-14 02:35:33 +020014723 if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
Victor Stinnera47082312012-10-04 02:19:54 +020014724 return -1;
Victor Stinnera47082312012-10-04 02:19:54 +020014725 return 1;
14726 }
14727 *p_str = PyUnicode_FromOrdinal(ch);
14728 break;
14729 }
14730
14731 default:
14732 PyErr_Format(PyExc_ValueError,
14733 "unsupported format character '%c' (0x%x) "
Victor Stinnera33bce02014-07-04 22:47:46 +020014734 "at index %zd",
Victor Stinnera47082312012-10-04 02:19:54 +020014735 (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
14736 (int)arg->ch,
14737 ctx->fmtpos - 1);
14738 return -1;
14739 }
14740 if (*p_str == NULL)
14741 return -1;
14742 assert (PyUnicode_Check(*p_str));
14743 return 0;
14744}
14745
14746static int
14747unicode_format_arg_output(struct unicode_formatter_t *ctx,
14748 struct unicode_format_arg_t *arg,
14749 PyObject *str)
14750{
14751 Py_ssize_t len;
14752 enum PyUnicode_Kind kind;
14753 void *pbuf;
14754 Py_ssize_t pindex;
14755 Py_UCS4 signchar;
14756 Py_ssize_t buflen;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014757 Py_UCS4 maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014758 Py_ssize_t sublen;
14759 _PyUnicodeWriter *writer = &ctx->writer;
14760 Py_UCS4 fill;
14761
14762 fill = ' ';
14763 if (arg->sign && arg->flags & F_ZERO)
14764 fill = '0';
14765
14766 if (PyUnicode_READY(str) == -1)
14767 return -1;
14768
14769 len = PyUnicode_GET_LENGTH(str);
14770 if ((arg->width == -1 || arg->width <= len)
14771 && (arg->prec == -1 || arg->prec >= len)
14772 && !(arg->flags & (F_SIGN | F_BLANK)))
14773 {
14774 /* Fast path */
14775 if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
14776 return -1;
14777 return 0;
14778 }
14779
14780 /* Truncate the string for "s", "r" and "a" formats
14781 if the precision is set */
14782 if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
14783 if (arg->prec >= 0 && len > arg->prec)
14784 len = arg->prec;
14785 }
14786
14787 /* Adjust sign and width */
14788 kind = PyUnicode_KIND(str);
14789 pbuf = PyUnicode_DATA(str);
14790 pindex = 0;
14791 signchar = '\0';
14792 if (arg->sign) {
14793 Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
14794 if (ch == '-' || ch == '+') {
14795 signchar = ch;
14796 len--;
14797 pindex++;
14798 }
14799 else if (arg->flags & F_SIGN)
14800 signchar = '+';
14801 else if (arg->flags & F_BLANK)
14802 signchar = ' ';
14803 else
14804 arg->sign = 0;
14805 }
14806 if (arg->width < len)
14807 arg->width = len;
14808
14809 /* Prepare the writer */
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014810 maxchar = writer->maxchar;
Victor Stinnera47082312012-10-04 02:19:54 +020014811 if (!(arg->flags & F_LJUST)) {
14812 if (arg->sign) {
14813 if ((arg->width-1) > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014814 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014815 }
14816 else {
14817 if (arg->width > len)
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014818 maxchar = Py_MAX(maxchar, fill);
Victor Stinnera47082312012-10-04 02:19:54 +020014819 }
14820 }
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014821 if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
14822 Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
Benjamin Peterson3164f5d2013-06-10 09:24:01 -070014823 maxchar = Py_MAX(maxchar, strmaxchar);
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014824 }
14825
Victor Stinnera47082312012-10-04 02:19:54 +020014826 buflen = arg->width;
14827 if (arg->sign && len == arg->width)
14828 buflen++;
Victor Stinnereb4b5ac2013-04-03 02:02:33 +020014829 if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
Victor Stinnera47082312012-10-04 02:19:54 +020014830 return -1;
14831
14832 /* Write the sign if needed */
14833 if (arg->sign) {
14834 if (fill != ' ') {
14835 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14836 writer->pos += 1;
14837 }
14838 if (arg->width > len)
14839 arg->width--;
14840 }
14841
14842 /* Write the numeric prefix for "x", "X" and "o" formats
14843 if the alternate form is used.
14844 For example, write "0x" for the "%#x" format. */
14845 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14846 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14847 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
14848 if (fill != ' ') {
14849 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14850 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14851 writer->pos += 2;
14852 pindex += 2;
14853 }
14854 arg->width -= 2;
14855 if (arg->width < 0)
14856 arg->width = 0;
14857 len -= 2;
14858 }
14859
14860 /* Pad left with the fill character if needed */
14861 if (arg->width > len && !(arg->flags & F_LJUST)) {
14862 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014863 unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014864 writer->pos += sublen;
14865 arg->width = len;
14866 }
14867
14868 /* If padding with spaces: write sign if needed and/or numeric prefix if
14869 the alternate form is used */
14870 if (fill == ' ') {
14871 if (arg->sign) {
14872 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
14873 writer->pos += 1;
14874 }
14875 if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
14876 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
14877 assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
14878 PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
14879 PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
14880 writer->pos += 2;
14881 pindex += 2;
14882 }
14883 }
14884
14885 /* Write characters */
14886 if (len) {
14887 _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
14888 str, pindex, len);
14889 writer->pos += len;
14890 }
14891
14892 /* Pad right with the fill character if needed */
14893 if (arg->width > len) {
14894 sublen = arg->width - len;
Victor Stinner59423e32018-11-26 13:40:01 +010014895 unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
Victor Stinnera47082312012-10-04 02:19:54 +020014896 writer->pos += sublen;
14897 }
14898 return 0;
14899}
14900
14901/* Helper of PyUnicode_Format(): format one arg.
14902 Return 0 on success, raise an exception and return -1 on error. */
14903static int
14904unicode_format_arg(struct unicode_formatter_t *ctx)
14905{
14906 struct unicode_format_arg_t arg;
14907 PyObject *str;
14908 int ret;
14909
Victor Stinner8dbd4212012-12-04 09:30:24 +010014910 arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014911 if (arg.ch == '%') {
14912 ctx->fmtpos++;
14913 ctx->fmtcnt--;
14914 if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
14915 return -1;
14916 return 0;
14917 }
Victor Stinner8dbd4212012-12-04 09:30:24 +010014918 arg.flags = 0;
14919 arg.width = -1;
14920 arg.prec = -1;
14921 arg.sign = 0;
14922 str = NULL;
14923
Victor Stinnera47082312012-10-04 02:19:54 +020014924 ret = unicode_format_arg_parse(ctx, &arg);
14925 if (ret == -1)
14926 return -1;
14927
14928 ret = unicode_format_arg_format(ctx, &arg, &str);
14929 if (ret == -1)
14930 return -1;
14931
14932 if (ret != 1) {
14933 ret = unicode_format_arg_output(ctx, &arg, str);
14934 Py_DECREF(str);
14935 if (ret == -1)
14936 return -1;
14937 }
14938
Serhiy Storchaka9f8ad3f2017-03-08 05:51:19 +020014939 if (ctx->dict && (ctx->argidx < ctx->arglen)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014940 PyErr_SetString(PyExc_TypeError,
14941 "not all arguments converted during string formatting");
14942 return -1;
14943 }
14944 return 0;
14945}
14946
Alexander Belopolsky40018472011-02-26 01:02:56 +000014947PyObject *
14948PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014949{
Victor Stinnera47082312012-10-04 02:19:54 +020014950 struct unicode_formatter_t ctx;
Tim Petersced69f82003-09-16 20:30:58 +000014951
Guido van Rossumd57fd912000-03-10 22:53:23 +000014952 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014953 PyErr_BadInternalCall();
14954 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014955 }
Victor Stinnera47082312012-10-04 02:19:54 +020014956
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014957 if (ensure_unicode(format) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014958 return NULL;
Serhiy Storchaka21a663e2016-04-13 15:37:23 +030014959
14960 ctx.fmtstr = format;
Victor Stinnera47082312012-10-04 02:19:54 +020014961 ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
14962 ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
14963 ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
14964 ctx.fmtpos = 0;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014965
Victor Stinner8f674cc2013-04-17 23:02:17 +020014966 _PyUnicodeWriter_Init(&ctx.writer);
14967 ctx.writer.min_length = ctx.fmtcnt + 100;
14968 ctx.writer.overallocate = 1;
Victor Stinnerf2c76aa2012-05-03 13:10:40 +020014969
Guido van Rossumd57fd912000-03-10 22:53:23 +000014970 if (PyTuple_Check(args)) {
Victor Stinnera47082312012-10-04 02:19:54 +020014971 ctx.arglen = PyTuple_Size(args);
14972 ctx.argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014973 }
14974 else {
Victor Stinnera47082312012-10-04 02:19:54 +020014975 ctx.arglen = -1;
14976 ctx.argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014977 }
Victor Stinnera47082312012-10-04 02:19:54 +020014978 ctx.args_owned = 0;
Benjamin Peterson28a6cfa2012-08-28 17:55:35 -040014979 if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
Victor Stinnera47082312012-10-04 02:19:54 +020014980 ctx.dict = args;
14981 else
14982 ctx.dict = NULL;
14983 ctx.args = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014984
Victor Stinnera47082312012-10-04 02:19:54 +020014985 while (--ctx.fmtcnt >= 0) {
14986 if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
Victor Stinnercfc4c132013-04-03 01:48:39 +020014987 Py_ssize_t nonfmtpos;
Victor Stinnera47082312012-10-04 02:19:54 +020014988
14989 nonfmtpos = ctx.fmtpos++;
14990 while (ctx.fmtcnt >= 0 &&
14991 PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
14992 ctx.fmtpos++;
14993 ctx.fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014994 }
Victor Stinnera47082312012-10-04 02:19:54 +020014995 if (ctx.fmtcnt < 0) {
14996 ctx.fmtpos--;
14997 ctx.writer.overallocate = 0;
Victor Stinnera0494432012-10-03 23:03:46 +020014998 }
Victor Stinneree4544c2012-05-09 22:24:08 +020014999
Victor Stinnercfc4c132013-04-03 01:48:39 +020015000 if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
15001 nonfmtpos, ctx.fmtpos) < 0)
15002 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015003 }
15004 else {
Victor Stinnera47082312012-10-04 02:19:54 +020015005 ctx.fmtpos++;
15006 if (unicode_format_arg(&ctx) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000015007 goto onError;
Victor Stinnera47082312012-10-04 02:19:54 +020015008 }
15009 }
Victor Stinneraff3cc62012-04-30 05:19:21 +020015010
Victor Stinnera47082312012-10-04 02:19:54 +020015011 if (ctx.argidx < ctx.arglen && !ctx.dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000015012 PyErr_SetString(PyExc_TypeError,
15013 "not all arguments converted during string formatting");
15014 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015015 }
15016
Victor Stinnera47082312012-10-04 02:19:54 +020015017 if (ctx.args_owned) {
15018 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015019 }
Victor Stinnera47082312012-10-04 02:19:54 +020015020 return _PyUnicodeWriter_Finish(&ctx.writer);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015021
Benjamin Peterson29060642009-01-31 22:14:21 +000015022 onError:
Victor Stinnera47082312012-10-04 02:19:54 +020015023 _PyUnicodeWriter_Dealloc(&ctx.writer);
15024 if (ctx.args_owned) {
15025 Py_DECREF(ctx.args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000015026 }
15027 return NULL;
15028}
15029
Jeremy Hylton938ace62002-07-17 16:30:39 +000015030static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000015031unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
15032
Tim Peters6d6c1a32001-08-02 04:15:00 +000015033static PyObject *
15034unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15035{
Benjamin Peterson29060642009-01-31 22:14:21 +000015036 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015037 static char *kwlist[] = {"object", "encoding", "errors", 0};
15038 char *encoding = NULL;
15039 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000015040
Benjamin Peterson14339b62009-01-31 16:36:08 +000015041 if (type != &PyUnicode_Type)
15042 return unicode_subtype_new(type, args, kwds);
15043 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000015044 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000015045 return NULL;
15046 if (x == NULL)
Serhiy Storchaka678db842013-01-26 12:16:36 +020015047 _Py_RETURN_UNICODE_EMPTY();
Benjamin Peterson14339b62009-01-31 16:36:08 +000015048 if (encoding == NULL && errors == NULL)
15049 return PyObject_Str(x);
15050 else
Benjamin Peterson29060642009-01-31 22:14:21 +000015051 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000015052}
15053
Guido van Rossume023fe02001-08-30 03:12:59 +000015054static PyObject *
15055unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
15056{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015057 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015058 Py_ssize_t length, char_size;
15059 int share_wstr, share_utf8;
15060 unsigned int kind;
15061 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000015062
Benjamin Peterson14339b62009-01-31 16:36:08 +000015063 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015064
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015065 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015066 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000015067 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015068 assert(_PyUnicode_CHECK(unicode));
Benjamin Petersonbac79492012-01-14 13:34:47 -050015069 if (PyUnicode_READY(unicode) == -1) {
Benjamin Peterson22a29702012-01-02 09:00:30 -060015070 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015071 return NULL;
Benjamin Peterson22a29702012-01-02 09:00:30 -060015072 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015073
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015074 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015075 if (self == NULL) {
15076 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015077 return NULL;
15078 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015079 kind = PyUnicode_KIND(unicode);
15080 length = PyUnicode_GET_LENGTH(unicode);
15081
15082 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015083#ifdef Py_DEBUG
15084 _PyUnicode_HASH(self) = -1;
15085#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015086 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015087#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015088 _PyUnicode_STATE(self).interned = 0;
15089 _PyUnicode_STATE(self).kind = kind;
15090 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020015091 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015092 _PyUnicode_STATE(self).ready = 1;
15093 _PyUnicode_WSTR(self) = NULL;
15094 _PyUnicode_UTF8_LENGTH(self) = 0;
15095 _PyUnicode_UTF8(self) = NULL;
15096 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020015097 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015098
15099 share_utf8 = 0;
15100 share_wstr = 0;
15101 if (kind == PyUnicode_1BYTE_KIND) {
15102 char_size = 1;
15103 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
15104 share_utf8 = 1;
15105 }
15106 else if (kind == PyUnicode_2BYTE_KIND) {
15107 char_size = 2;
15108 if (sizeof(wchar_t) == 2)
15109 share_wstr = 1;
15110 }
15111 else {
15112 assert(kind == PyUnicode_4BYTE_KIND);
15113 char_size = 4;
15114 if (sizeof(wchar_t) == 4)
15115 share_wstr = 1;
15116 }
15117
15118 /* Ensure we won't overflow the length. */
15119 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
15120 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015121 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015122 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015123 data = PyObject_MALLOC((length + 1) * char_size);
15124 if (data == NULL) {
15125 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015126 goto onError;
15127 }
15128
Victor Stinnerc3c74152011-10-02 20:39:55 +020015129 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015130 if (share_utf8) {
15131 _PyUnicode_UTF8_LENGTH(self) = length;
15132 _PyUnicode_UTF8(self) = data;
15133 }
15134 if (share_wstr) {
15135 _PyUnicode_WSTR_LENGTH(self) = length;
15136 _PyUnicode_WSTR(self) = (wchar_t *)data;
15137 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015138
Christian Heimesf051e432016-09-13 20:22:02 +020015139 memcpy(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020015140 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020015141 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020015142#ifdef Py_DEBUG
15143 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
15144#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020015145 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010015146 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020015147
15148onError:
15149 Py_DECREF(unicode);
15150 Py_DECREF(self);
15151 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000015152}
15153
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000015154PyDoc_STRVAR(unicode_doc,
Chris Jerdonek83fe2e12012-10-07 14:48:36 -070015155"str(object='') -> str\n\
15156str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000015157\n\
Nick Coghlan573b1fd2012-08-16 14:13:07 +100015158Create a new string object from the given object. If encoding or\n\
15159errors is specified, then the object must expose a data buffer\n\
15160that will be decoded using the given encoding and error handler.\n\
15161Otherwise, returns the result of object.__str__() (if defined)\n\
15162or repr(object).\n\
15163encoding defaults to sys.getdefaultencoding().\n\
15164errors defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000015165
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015166static PyObject *unicode_iter(PyObject *seq);
15167
Guido van Rossumd57fd912000-03-10 22:53:23 +000015168PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000015169 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Bupfc93bd42018-06-19 03:59:55 -050015170 "str", /* tp_name */
15171 sizeof(PyUnicodeObject), /* tp_basicsize */
15172 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015173 /* Slots */
Bupfc93bd42018-06-19 03:59:55 -050015174 (destructor)unicode_dealloc, /* tp_dealloc */
15175 0, /* tp_print */
15176 0, /* tp_getattr */
15177 0, /* tp_setattr */
15178 0, /* tp_reserved */
15179 unicode_repr, /* tp_repr */
15180 &unicode_as_number, /* tp_as_number */
15181 &unicode_as_sequence, /* tp_as_sequence */
15182 &unicode_as_mapping, /* tp_as_mapping */
15183 (hashfunc) unicode_hash, /* tp_hash*/
15184 0, /* tp_call*/
15185 (reprfunc) unicode_str, /* tp_str */
15186 PyObject_GenericGetAttr, /* tp_getattro */
15187 0, /* tp_setattro */
15188 0, /* tp_as_buffer */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015189 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Bupfc93bd42018-06-19 03:59:55 -050015190 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
15191 unicode_doc, /* tp_doc */
15192 0, /* tp_traverse */
15193 0, /* tp_clear */
15194 PyUnicode_RichCompare, /* tp_richcompare */
15195 0, /* tp_weaklistoffset */
15196 unicode_iter, /* tp_iter */
15197 0, /* tp_iternext */
15198 unicode_methods, /* tp_methods */
15199 0, /* tp_members */
15200 0, /* tp_getset */
15201 &PyBaseObject_Type, /* tp_base */
15202 0, /* tp_dict */
15203 0, /* tp_descr_get */
15204 0, /* tp_descr_set */
15205 0, /* tp_dictoffset */
15206 0, /* tp_init */
15207 0, /* tp_alloc */
15208 unicode_new, /* tp_new */
15209 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000015210};
15211
15212/* Initialize the Unicode implementation */
15213
Victor Stinner3a50e702011-10-18 21:21:00 +020015214int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015215{
Thomas Wouters477c8d52006-05-27 19:21:47 +000015216 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015217 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000015218 0x000A, /* LINE FEED */
15219 0x000D, /* CARRIAGE RETURN */
15220 0x001C, /* FILE SEPARATOR */
15221 0x001D, /* GROUP SEPARATOR */
15222 0x001E, /* RECORD SEPARATOR */
15223 0x0085, /* NEXT LINE */
15224 0x2028, /* LINE SEPARATOR */
15225 0x2029, /* PARAGRAPH SEPARATOR */
15226 };
15227
Fred Drakee4315f52000-05-09 19:53:39 +000015228 /* Init the implementation */
Serhiy Storchaka678db842013-01-26 12:16:36 +020015229 _Py_INCREF_UNICODE_EMPTY();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015230 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015231 Py_FatalError("Can't create empty string");
Serhiy Storchaka678db842013-01-26 12:16:36 +020015232 Py_DECREF(unicode_empty);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015233
Guido van Rossumcacfc072002-05-24 19:01:59 +000015234 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000015235 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000015236
15237 /* initialize the linebreak bloom filter */
15238 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015239 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020015240 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000015241
Christian Heimes26532f72013-07-20 14:57:16 +020015242 if (PyType_Ready(&EncodingMapType) < 0)
15243 Py_FatalError("Can't initialize encoding map type");
Victor Stinner3a50e702011-10-18 21:21:00 +020015244
Benjamin Petersonc4311282012-10-30 23:21:10 -040015245 if (PyType_Ready(&PyFieldNameIter_Type) < 0)
15246 Py_FatalError("Can't initialize field name iterator type");
15247
15248 if (PyType_Ready(&PyFormatterIter_Type) < 0)
15249 Py_FatalError("Can't initialize formatter iter type");
Benjamin Petersone8ea97f2012-10-30 23:27:52 -040015250
Victor Stinner3a50e702011-10-18 21:21:00 +020015251 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015252}
15253
15254/* Finalize the Unicode implementation */
15255
Christian Heimesa156e092008-02-16 07:38:31 +000015256int
15257PyUnicode_ClearFreeList(void)
15258{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015259 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000015260}
15261
Guido van Rossumd57fd912000-03-10 22:53:23 +000015262void
Thomas Wouters78890102000-07-22 19:25:51 +000015263_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000015264{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000015265 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000015266
Serhiy Storchaka05997252013-01-26 12:14:02 +020015267 Py_CLEAR(unicode_empty);
Barry Warsaw5b4c2282000-10-03 20:45:26 +000015268
Serhiy Storchaka05997252013-01-26 12:14:02 +020015269 for (i = 0; i < 256; i++)
15270 Py_CLEAR(unicode_latin1[i]);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020015271 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000015272 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000015273}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000015274
Walter Dörwald16807132007-05-25 13:52:07 +000015275void
15276PyUnicode_InternInPlace(PyObject **p)
15277{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015278 PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015279 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020015280#ifdef Py_DEBUG
15281 assert(s != NULL);
15282 assert(_PyUnicode_CHECK(s));
15283#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000015284 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020015285 return;
15286#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000015287 /* If it's a subclass, we don't really know what putting
15288 it in the interned dict might do. */
15289 if (!PyUnicode_CheckExact(s))
15290 return;
15291 if (PyUnicode_CHECK_INTERNED(s))
15292 return;
15293 if (interned == NULL) {
15294 interned = PyDict_New();
15295 if (interned == NULL) {
15296 PyErr_Clear(); /* Don't leave an exception */
15297 return;
15298 }
15299 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015300 Py_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015301 t = PyDict_SetDefault(interned, s, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015302 Py_END_ALLOW_RECURSION
Berker Peksagced8d4c2016-07-25 04:40:39 +030015303 if (t == NULL) {
15304 PyErr_Clear();
15305 return;
15306 }
15307 if (t != s) {
Victor Stinnerf0335102013-04-14 19:13:03 +020015308 Py_INCREF(t);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +030015309 Py_SETREF(*p, t);
Victor Stinnerf0335102013-04-14 19:13:03 +020015310 return;
15311 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000015312 /* The two references in interned are not counted by refcnt.
15313 The deallocator will take care of this */
15314 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015315 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000015316}
15317
15318void
15319PyUnicode_InternImmortal(PyObject **p)
15320{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015321 PyUnicode_InternInPlace(p);
15322 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020015323 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015324 Py_INCREF(*p);
15325 }
Walter Dörwald16807132007-05-25 13:52:07 +000015326}
15327
15328PyObject *
15329PyUnicode_InternFromString(const char *cp)
15330{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015331 PyObject *s = PyUnicode_FromString(cp);
15332 if (s == NULL)
15333 return NULL;
15334 PyUnicode_InternInPlace(&s);
15335 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000015336}
15337
Alexander Belopolsky40018472011-02-26 01:02:56 +000015338void
15339_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000015340{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015341 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015342 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015343 Py_ssize_t i, n;
15344 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000015345
Benjamin Peterson14339b62009-01-31 16:36:08 +000015346 if (interned == NULL || !PyDict_Check(interned))
15347 return;
15348 keys = PyDict_Keys(interned);
15349 if (keys == NULL || !PyList_Check(keys)) {
15350 PyErr_Clear();
15351 return;
15352 }
Walter Dörwald16807132007-05-25 13:52:07 +000015353
Benjamin Peterson14339b62009-01-31 16:36:08 +000015354 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
15355 detector, interned unicode strings are not forcibly deallocated;
15356 rather, we give them their stolen references back, and then clear
15357 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000015358
Benjamin Peterson14339b62009-01-31 16:36:08 +000015359 n = PyList_GET_SIZE(keys);
15360 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000015361 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015362 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015363 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015364 if (PyUnicode_READY(s) == -1) {
Barry Warsawb2e57942017-09-14 18:13:16 -070015365 Py_UNREACHABLE();
Victor Stinner6b56a7f2011-10-04 20:04:52 +020015366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015367 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015368 case SSTATE_NOT_INTERNED:
15369 /* XXX Shouldn't happen */
15370 break;
15371 case SSTATE_INTERNED_IMMORTAL:
15372 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015373 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015374 break;
15375 case SSTATE_INTERNED_MORTAL:
15376 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015377 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015378 break;
15379 default:
15380 Py_FatalError("Inconsistent interned string state.");
15381 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015382 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015383 }
15384 fprintf(stderr, "total size of all interned strings: "
15385 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
15386 "mortal/immortal\n", mortal_size, immortal_size);
15387 Py_DECREF(keys);
15388 PyDict_Clear(interned);
Serhiy Storchaka05997252013-01-26 12:14:02 +020015389 Py_CLEAR(interned);
Walter Dörwald16807132007-05-25 13:52:07 +000015390}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015391
15392
15393/********************* Unicode Iterator **************************/
15394
15395typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015396 PyObject_HEAD
15397 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015398 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015399} unicodeiterobject;
15400
15401static void
15402unicodeiter_dealloc(unicodeiterobject *it)
15403{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015404 _PyObject_GC_UNTRACK(it);
15405 Py_XDECREF(it->it_seq);
15406 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015407}
15408
15409static int
15410unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
15411{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015412 Py_VISIT(it->it_seq);
15413 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015414}
15415
15416static PyObject *
15417unicodeiter_next(unicodeiterobject *it)
15418{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015419 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015420
Benjamin Peterson14339b62009-01-31 16:36:08 +000015421 assert(it != NULL);
15422 seq = it->it_seq;
15423 if (seq == NULL)
15424 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020015425 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015426
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015427 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
15428 int kind = PyUnicode_KIND(seq);
15429 void *data = PyUnicode_DATA(seq);
15430 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
15431 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015432 if (item != NULL)
15433 ++it->it_index;
15434 return item;
15435 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015436
Benjamin Peterson14339b62009-01-31 16:36:08 +000015437 it->it_seq = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030015438 Py_DECREF(seq);
Benjamin Peterson14339b62009-01-31 16:36:08 +000015439 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015440}
15441
15442static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015443unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015444{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015445 Py_ssize_t len = 0;
15446 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020015447 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015448 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015449}
15450
15451PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
15452
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015453static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +053015454unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015455{
15456 if (it->it_seq != NULL) {
Antoine Pitroua7013882012-04-05 00:04:20 +020015457 return Py_BuildValue("N(O)n", _PyObject_GetBuiltin("iter"),
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015458 it->it_seq, it->it_index);
15459 } else {
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015460 PyObject *u = (PyObject *)_PyUnicode_New(0);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015461 if (u == NULL)
15462 return NULL;
Antoine Pitroua7013882012-04-05 00:04:20 +020015463 return Py_BuildValue("N(N)", _PyObject_GetBuiltin("iter"), u);
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015464 }
15465}
15466
15467PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
15468
15469static PyObject *
15470unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
15471{
15472 Py_ssize_t index = PyLong_AsSsize_t(state);
15473 if (index == -1 && PyErr_Occurred())
15474 return NULL;
Kristján Valur Jónsson25dded02014-03-05 13:47:57 +000015475 if (it->it_seq != NULL) {
15476 if (index < 0)
15477 index = 0;
15478 else if (index > PyUnicode_GET_LENGTH(it->it_seq))
15479 index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
15480 it->it_index = index;
15481 }
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015482 Py_RETURN_NONE;
15483}
15484
15485PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
15486
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015487static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015488 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000015489 length_hint_doc},
Kristján Valur Jónsson31668b82012-04-03 10:49:41 +000015490 {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
15491 reduce_doc},
15492 {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
15493 setstate_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000015494 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015495};
15496
15497PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000015498 PyVarObject_HEAD_INIT(&PyType_Type, 0)
15499 "str_iterator", /* tp_name */
15500 sizeof(unicodeiterobject), /* tp_basicsize */
15501 0, /* tp_itemsize */
15502 /* methods */
15503 (destructor)unicodeiter_dealloc, /* tp_dealloc */
15504 0, /* tp_print */
15505 0, /* tp_getattr */
15506 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000015507 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000015508 0, /* tp_repr */
15509 0, /* tp_as_number */
15510 0, /* tp_as_sequence */
15511 0, /* tp_as_mapping */
15512 0, /* tp_hash */
15513 0, /* tp_call */
15514 0, /* tp_str */
15515 PyObject_GenericGetAttr, /* tp_getattro */
15516 0, /* tp_setattro */
15517 0, /* tp_as_buffer */
15518 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
15519 0, /* tp_doc */
15520 (traverseproc)unicodeiter_traverse, /* tp_traverse */
15521 0, /* tp_clear */
15522 0, /* tp_richcompare */
15523 0, /* tp_weaklistoffset */
15524 PyObject_SelfIter, /* tp_iter */
15525 (iternextfunc)unicodeiter_next, /* tp_iternext */
15526 unicodeiter_methods, /* tp_methods */
15527 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015528};
15529
15530static PyObject *
15531unicode_iter(PyObject *seq)
15532{
Benjamin Peterson14339b62009-01-31 16:36:08 +000015533 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015534
Benjamin Peterson14339b62009-01-31 16:36:08 +000015535 if (!PyUnicode_Check(seq)) {
15536 PyErr_BadInternalCall();
15537 return NULL;
15538 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015539 if (PyUnicode_READY(seq) == -1)
15540 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015541 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
15542 if (it == NULL)
15543 return NULL;
15544 it->it_index = 0;
15545 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015546 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000015547 _PyObject_GC_TRACK(it);
15548 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000015549}
15550
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015551
15552size_t
15553Py_UNICODE_strlen(const Py_UNICODE *u)
15554{
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015555 return wcslen(u);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015556}
15557
15558Py_UNICODE*
15559Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
15560{
15561 Py_UNICODE *u = s1;
15562 while ((*u++ = *s2++));
15563 return s1;
15564}
15565
15566Py_UNICODE*
15567Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15568{
15569 Py_UNICODE *u = s1;
15570 while ((*u++ = *s2++))
15571 if (n-- == 0)
15572 break;
15573 return s1;
15574}
15575
15576Py_UNICODE*
15577Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
15578{
15579 Py_UNICODE *u1 = s1;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015580 u1 += wcslen(u1);
15581 while ((*u1++ = *s2++));
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015582 return s1;
15583}
15584
15585int
15586Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
15587{
15588 while (*s1 && *s2 && *s1 == *s2)
15589 s1++, s2++;
15590 if (*s1 && *s2)
15591 return (*s1 < *s2) ? -1 : +1;
15592 if (*s1)
15593 return 1;
15594 if (*s2)
15595 return -1;
15596 return 0;
15597}
15598
15599int
15600Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
15601{
Antoine Pitrou9ed5f272013-08-13 20:18:52 +020015602 Py_UNICODE u1, u2;
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015603 for (; n != 0; n--) {
15604 u1 = *s1;
15605 u2 = *s2;
15606 if (u1 != u2)
15607 return (u1 < u2) ? -1 : +1;
15608 if (u1 == '\0')
15609 return 0;
15610 s1++;
15611 s2++;
15612 }
15613 return 0;
15614}
15615
15616Py_UNICODE*
15617Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
15618{
15619 const Py_UNICODE *p;
15620 for (p = s; *p; p++)
15621 if (*p == c)
15622 return (Py_UNICODE*)p;
15623 return NULL;
15624}
15625
15626Py_UNICODE*
15627Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
15628{
15629 const Py_UNICODE *p;
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +020015630 p = s + wcslen(s);
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010015631 while (p != s) {
15632 p--;
15633 if (*p == c)
15634 return (Py_UNICODE*)p;
15635 }
15636 return NULL;
15637}
Victor Stinner331ea922010-08-10 16:37:20 +000015638
Victor Stinner71133ff2010-09-01 23:43:53 +000015639Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020015640PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000015641{
Victor Stinner577db2c2011-10-11 22:12:48 +020015642 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015643 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000015644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020015645 if (!PyUnicode_Check(unicode)) {
15646 PyErr_BadArgument();
15647 return NULL;
15648 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015649 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020015650 if (u == NULL)
15651 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000015652 /* Ensure we won't overflow the size. */
Gregory P. Smith8486f9b2014-09-30 00:33:24 -070015653 if (len > ((PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000015654 PyErr_NoMemory();
15655 return NULL;
15656 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020015657 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000015658 size *= sizeof(Py_UNICODE);
15659 copy = PyMem_Malloc(size);
15660 if (copy == NULL) {
15661 PyErr_NoMemory();
15662 return NULL;
15663 }
Victor Stinner577db2c2011-10-11 22:12:48 +020015664 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000015665 return copy;
15666}
Martin v. Löwis5b222132007-06-10 09:51:05 +000015667
Georg Brandl66c221e2010-10-14 07:04:07 +000015668/* A _string module, to export formatter_parser and formatter_field_name_split
15669 to the string.Formatter class implemented in Python. */
15670
15671static PyMethodDef _string_methods[] = {
15672 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
15673 METH_O, PyDoc_STR("split the argument as a field name")},
15674 {"formatter_parser", (PyCFunction) formatter_parser,
15675 METH_O, PyDoc_STR("parse the argument as a format string")},
15676 {NULL, NULL}
15677};
15678
15679static struct PyModuleDef _string_module = {
15680 PyModuleDef_HEAD_INIT,
15681 "_string",
15682 PyDoc_STR("string helper module"),
15683 0,
15684 _string_methods,
15685 NULL,
15686 NULL,
15687 NULL,
15688 NULL
15689};
15690
15691PyMODINIT_FUNC
15692PyInit__string(void)
15693{
15694 return PyModule_Create(&_string_module);
15695}
15696
15697
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000015698#ifdef __cplusplus
15699}
15700#endif